Posts

Showing posts with the label DataGridView

Donate

AllowUsersToAddRows In DataGridView Not Working If DataSource is List<T>

Greetings! Going back to a previous project of mine, I found out that some DataGridView control's DataSource where set using List<T> and as a result, prevented the users to add new data to the DataGridView. private void List() { List<Item> list = new List<Item>(); for ( int i = 0; i < 100; i++) { list.Add( new Item() { ID = i, Name = String.Format( "{0}:{1}" , "Test" , i.ToString()) }); } DataGridView1.DataSource = list; } The common solution is to use DataTable as the DataSource but if we want to use a List type object, we could use BindingList<T> or BindingSource. Both of these have AllowNew property which indicates that you can add items to the list using the AddNew() method. It is stated in DataGridView.AllowUsersToAddRows that " If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true. ".Well, Lis

DataGridView ComboBox Cascade In Windows Forms

Image
Good day to all! Here's an example of how to perform a combobox lookup or cascade using two DataGridViewComboBoxColumns inside a DataGridView control Combo Lookup in DGV . The solution presented is in VB.NET, so I decided to create a C# equivalent for this. In form load event, populate two DataTables for Roles and Employees. Each employee is assigned to a specific role. private void Form1_Load( object sender, EventArgs e) { DataGridView1.Rows.Add(); dtRole.Columns.Add( "RoleID" ); dtRole.Columns.Add( "RoleName" ); dtRole.Rows.Add(1, "Admin" ); dtRole.Rows.Add(2, "Instructor" ); dtRole.Rows.Add(3, "Utility" ); dtEmployee.Columns.Add( "RoleID" ); dtEmployee.Columns.Add( "EmployeeID" ); dtEmployee.Columns.Add( "EmployeeName" ); dtEmployee.Rows.Add(1, 1, "Sam" ); dtEmployee.Rows.Add(1, 2, "Nicole" ); dtEmployee.Rows.Add(2, 3, "Donald" ); dtEmployee.Rows.Add(

DataGridViewComboBoxColumn Show Dropdown In Single Click Instead Of Double Click

Hi, When adding DataGridViewComboBoxColumn control to a DataGridView control, the dropdown shows when you double click instead of single click. The common fix to this is to set the EditMode property to EditOnEnter . Given that you don't want to alter the default settings of the DataGrid control and you want to handle it through code,I found the solution in this website DATAGRIDVIEWCOMBOBOXCOLUMN REQUIRES MULTIPLE CLICKS TO SELECT AN ITEM from a comment made by a developer. However, there's a slight issue in the code provided since a column index returned might have a -1 index and this will cause an Unhandled Exception . The revision made is to add a condition that will check if the ColumnIndex of the DataGridView cell is greater than or equal to 0. private void DataGridView1_CellClick( object sender, DataGridViewCellEventArgs e) { DataGridView grid = (DataGridView)sender; if (e.ColumnIndex >= 0) { if (grid.Columns[e.ColumnIndex].Name == "Role" || grid.

Change DataGridViewRow FontStyle To Bold In CellFormatting Event

Hello, There was a question raised in the forums on how to change the FontStyle of a DataGridViewRow to Bold in the CellFormatting event. A solution is to set the Font property of a row with a Font object setting it's second parameter to FontStyle.Bold. private void EmployeeDTRDataGridView_CellFormatting( object sender, DataGridViewCellFormattingEventArgs e) { if (EmployeeDTRDataGridView.Columns[e.ColumnIndex].Name == "OnLeave" ) { if (e.Value != System.DBNull.Value) { if (Convert.ToBoolean(e.Value) == true ) { EmployeeDTRDataGridView.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold); } } } }

How To Wrap Text In A DataGridViewColumn

Image
Given that you have data such as comments/notes/description/address that would comprise at least hundreds of characters and you want to show them on the DataGridView control, you will notice that the text is concatenated and replaced with ellipses. In order to achieve wrapping of text in a DataGridView cell, I achieved it using these steps. 1. Change the WrapMode value to True of a DataGridViewTextBoxColumn's DefaultCellStyle. 2. In my DataBindingComplete event of the DataGridView, set the AutoSizeRowsMode of the DataGridView to AllCells. C# Code private void dgvFormat_DataBindingComplete( object sender, DataGridViewBindingCompleteEventArgs e) { dgvFormat.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; } That's it.. :-)

DataGridview Check For Duplicate Values And Group Code In Separate Column

Image
Hi, I've always been a desktop developer ever since Visual Basic 6.0 came into existence. While I'm busy doing projects for the web platform, I always go back to my roots of solving desktop issues in .NET. :-D Well, going back to the issue, a certain member in Visual Basic forums posted an issue on how to check duplicate values in a particular datagridview column with DateTime as type. Once a duplicate value has been detected, the code number will be grouped in another datagridview column with label total. See sample screenshot for the desired output: After creating the logic, I proceed to converting it to code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 private void SpotDuplicates() { int i = 0; int j = 0; for (i = 0; i <= dgvDates.RowCount - 1; i++) { for (j = 0; j <= dgvDates.RowCount - 1; j++) { if (i > j) { if (Convert.ToDateTime(dgvDates[0

Custom CheckedListBox DataGridView Column

Image
Hello, Here's a working custom control class on how to embed CheckedListBox as a datagridview column. Source: Need a DataGridView Custom Column of Type ListView or CheckedListBox However, this class lacked functionalities such as obtaining the checked items and preserving the checked items during painting of the datagridview cell. Here's the custom class: public class CheckedListBoxColumn : DataGridViewColumn { public CheckedListBoxColumn() : base ( new CheckedListBoxCell()) { } public override DataGridViewCell CellTemplate { get { return base .CellTemplate; } set { if ( value != null && ! value .GetType().IsAssignableFrom( typeof (CheckedListBoxCell))) { throw new InvalidCastException( "Must be

DataGridview Current Row Returns Null In SelectionChanged Event

When retrieving selected row cell values in the DataGridview, you might encounter object not set to reference of an instance. It's because the current row has not been initialized. Check first the cell value of the current row if it has cell contents. private void dgvAccounts_SelectionChanged( object sender, EventArgs e) { string countryName = string .Empty; if (dgvAccounts.SelectedRows.Count > 0) { if (dgvAccounts.CurrentRow.Cells[1].Value != null ) { countryName = dgvAccounts.CurrentRow.Cells[1].Value.ToString(); } } } This will ensure that databinding has finished. Cheers!

DataGridview Paging Using BindingSource And BindingNavigator In VB.NET

Image
Hi, In reference to the previous post on DataGridView paging using C# Datagridview paging using BindingSource in C# , I developed a Visual Basic.NET version for VB.NET Developers. Main Form Class: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 Option Infer On Imports System.Configuration Imports System.ComponentModel Imports MySql Imports MySql.Data Imports MySql.Data.MySqlClient Public Class FBinding Public Property TotalRecords() As Integer Public Const PageSize = 10 Private sourceData As New List( Of String ) Private dtSource As New DataTable Dim page As New PageOffsetList() Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initiali

DataGridview Paging Using BindingSource And BindingNavigator In C#

Image
Hello, VB.NET Version Here: DataGridview Paging Using BindingSource And BindingNavigator In VB.NET Here's a simple way to integrate paging in Datagridview using BindingNavigator and BindingSource. The original source can be found here: How can we do paging in datagridview in winform . I made some modifications to simulate loading of thousands of records from a database. Main Form Class: public partial class FBinding : Form { public static int totalRecords { get ; set ; } public const int pageSize = 10; private List< string > sourceData = new List< string >(); private DataTable dtSource = new DataTable(); public FBinding() { InitializeComponent(); bindingNav.BindingSource = bindingWebsite; bindingWebsite.CurrentChanged += new EventHandler(bindingWebsite_CurrentChanged); SetSource(); bindingWebsite.DataSource = new PageOffsetList(); } void bindingWebsite_CurrentChanged( object sender, EventAr

Embedding A DataGridview In Combobox Item In Windows Forms

Image
Hi, There's a post in codeproject that will host a datagridview in a combobox. It is in vb.net and I converted it to C#. I made some changes on the custom controls to retrieve the datagridview selected row. This was not provided in the author's post, so I made some changes myself. In total, the control was purely awesome. So, here's the C# equivalent. I won't be posting all the codes since the custom control is posted in codeproject. I'll be posting the main class instead. Credits: Niemand25 of Lithuania using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; namespace MyGridComboBoxCSharp { [ToolboxItem(true)] [ToolboxBitmap(typeof(ComboBox))] [DefaultBindingProperty("SelectedValue")] [LookupBindingProperties("DataSource", "

Custom DatagridviewCheckboxColumn In Windows Forms

Image
Hello, Here's a simple class implementation of a DatagridviewCheckboxColumn. public class DatagridviewCustomCheckboxColumn : DataGridViewCheckBoxColumn { public DatagridviewCustomCheckboxColumn() { this .CellTemplate = new DatagridviewCheckboxCustomCell(); } } class DatagridviewCheckboxCustomCell : DataGridViewCheckBoxCell { public int row_index { get ; set ; } public int CheckboxHeight { get { //your_desired_checkbox_height is a variable //that contains the desired height of your checkbox //you may set or get the property value.. return your_desired_checkbox_height; } } public int CheckboxWidth { get { //your_desired_checkbox_width is a variable //that contains the desired width of your checkbox //you may set or get the property value.. return your_d

Prevent DataGridView Last Row From Being Sorted On Column Click

Image
Hello, You might have a row in the DataGridView typically the last one that computes total and the grid control is unbound to a datasource. And then if a sorting event occurs, you dont' wanna include that row during sort event. So given that your application has a form and a DataGridView control, the code to perform databinding is handled in the Form Load Event. DataGridViewRow dgRowTotalCount; DataTable dataTable; private void Form1_Load ( object sender, EventArgs e) { DataTable dt = new DataTable( "tblEntTable" ); dt.Columns.Add( "ID" , typeof ( string )); dt.Columns.Add( "Amount" , typeof ( decimal )); dt.Rows.Add( new object [] { "1" , 100.51 }); dt.Rows.Add( new object [] { "2" , 200.52 }); dt.Rows.Add( new object [] { "6" , 500.24 }); dt.Rows.Add( new object [] { "8" , 1000.11 }); dt.Rows.Add( new object [] { "4" , 400.31 }); dt.Rows.Add( new object [] { "5" , 6

How To Apply Fore Color Or Font Weight To DataGridView Cell

Here's the code to apply font weight and font color to your datagridview cell. DataGridViewCellStyle style = new DataGridViewCellStyle(); style.ForeColor = Color.Red; style.Font = new Font( this .Font, FontStyle.Bold); dg.Rows[dg.Rows.Count - 1].Cells[i + 2].Style = style;

Method's type signature is not Interop compatible. [Copying DataGridValues to excel cell object]]

I have this original snippet which copies datagridview values into the microsoft excel sheet: for ( int i = 0; i < dataGridViewObjects[gcount].Columns.Count; i++) { sheet.Cells[1, i + 1] = dataGridViewObjects[gcount].Columns[i].Name; for ( int row = 0; row < dataGridViewObjects[gcount].Rows.Count; row++) { for ( int column = 0; column < dataGridViewObjects[gcount].Columns.Count; column++) { sheet.Cells[row + 2, column + 1] =dataGridViewObjects[gcount].Rows[row].Cells[column].Value; } } } The code above throws an exception of method type signature is not interop compatible. I was debugging and checking MSDN classes on Workbook. When I debugged at adding cell values, i did catch the exception. The solution is simple. Just add ToString() after the value, since value is of type object. sheet.Cells[row + 2, column + 1] = dataGridViewObjects[gcount].Rows[row].Cells[column].Value.ToString();

Donate