DataGridView control is a Windows Forms control that gives you the ability to customize and edit tabular data. It gives you number of properties, methods and events to customize its appearance and behavior. In this article, we will discuss some frequently asked questions and their solutions. These questions have been collected from a variety of sources including some newsgroups, MSDN site and a few, answered by me at the MSDN forums.
Tip 1 – Populating a DataGridView
In this short snippet, we will populate a DataGridView using the LoadData() method. This method uses the SqlDataAdapter to populate a DataSet. The table ‘Orders’ in the DataSet is then bound to the BindingSource component which gives us the flexibility to choose/modify the data location.
C#
publicpartialclassForm1:Form
{
privateSqlDataAdapterda;
privateSqlConnectionconn;
BindingSourcebsource =newBindingSource();
DataSetds =null;
stringsql;
publicForm1()
{
InitializeComponent();
}
privatevoidbtnLoad_Click(objectsender,EventArgse)
{
LoadData();
}
privatevoidLoadData()
{
stringconnectionString ="Data Source=localhost;Initial Catalog=Northwind;"+"Integrated Security=SSPI;";
conn =newSqlConnection(connectionString);
sql ="SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight,"+"ShipName, ShipCountry FROM Orders";
da =newSqlDataAdapter(sql, conn);
conn.Open();
ds =newDataSet();
SqlCommandBuildercommandBuilder =newSqlCommandBuilder(da);
da.Fill(ds,"Orders");
bsource.DataSource = ds.Tables["Orders"];
dgv.DataSource = bsource;
}
}
VB.NET
PublicPartialClassForm1
InheritsForm
PrivatedaAsSqlDataAdapter
PrivateconnAsSqlConnection
PrivatebsourceAsBindingSource =NewBindingSource()
PrivatedsAsDataSet =Nothing
PrivatesqlAsString
PublicSubNew()
InitializeComponent()
EndSub
PrivateSubbtnLoad_Click(ByValsenderAsObject,ByValeAsEventArgs)
LoadData()
EndSub
PrivateSubLoadData()
DimconnectionStringAsString= "Data Source=localhost;Initial Catalog=Northwind;" & "Integrated Security=SSPI;"
conn =NewSqlConnection(connectionString)
sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," & "ShipName, ShipCountry FROM Orders"
da =NewSqlDataAdapter(sql, conn)
conn.Open()
ds =NewDataSet()
DimcommandBuilderAsSqlCommandBuilder =NewSqlCommandBuilder(da)
da.Fill(ds, "Orders")
bsource.DataSource = ds.Tables("Orders")
dgv.DataSource = bsource
EndSub
EndClass
Tip 2 – Update the data in the DataGridView and save changes in the database
After editing the data in the cells, if you would like to update the changes permanently in the database, use the following code:
C#
privatevoidbtnUpdate_Click(objectsender,EventArgse)
{
DataTabledt = ds.Tables["Orders"];
this.dgv.BindingContext[dt].EndCurrentEdit();
this.da.Update(dt);
}
VB.NET
PrivateSubbtnUpdate_Click(ByValsenderAsObject,ByValeAsEventArgs)
DimdtAsDataTable = ds.Tables("Orders")
Me.dgv.BindingContext(dt).EndCurrentEdit()
Me.da.Update(dt)
EndSub
Tip 3 – Display a confirmation box before deleting a row in the DataGridView
Handle the UserDeletingRow event to display a confirmation box to the user. If the user confirms the deletion, delete the row. If the user clicks cancel, set e.cancel = true which cancels the row deletion.
C#
privatevoiddgv_UserDeletingRow(objectsender,DataGridViewRowCancelEventArgse)
{
if(!e.Row.IsNewRow)
{
DialogResultres =MessageBox.Show("Are you sure you want to delete this row?","Delete confirmation",
MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if(res ==DialogResult.No)
e.Cancel =true;
}
}
VB.NET
PrivateSubdgv_UserDeletingRow(ByValsenderAsObject,ByValeAsDataGridViewRowCancelEventArgs)
If(Note.Row.IsNewRow)Then
DimresAsDialogResult = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Ifres = DialogResult.NoThen
e.Cancel =True
EndIf
EndIf
EndSub
Tip 4 – How to autoresize column width in the DataGridView
The snippet shown below, first auto-resizes the columns to fit its content. Then the AutoSizeColumnsMode is set to the ‘DataGridViewAutoSizeColumnsMode.AllCells’ enumeration value which automatically adjust the widths of the columns when the data changes.
C#
privatevoidbtnResize_Click(objectsender,EventArgse)
{
dgv.AutoResizeColumns();
dgv.AutoSizeColumnsMode =DataGridViewAutoSizeColumnsMode.AllCells;
}
VB.NET
PrivateSubbtnResize_Click(ByValsenderAsObject,ByValeAsEventArgs)
dgv.AutoResizeColumns()
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
EndSub
Tip 5 - Select and Highlight an entire row in DataGridView
C#
introwToBeSelected = 3;// third row
if(dgv.Rows.Count >= rowToBeSelected)
{
// Since index is zero based, you have to subtract 1
dgv.Rows[rowToBeSelected - 1].Selected =true;
}
VB.NET
DimrowToBeSelectedAsInteger= 3' third row
Ifdgv.Rows.Count >= rowToBeSelectedThen
' Since index is zero based, you have to subtract 1
dgv.Rows(rowToBeSelected - 1).Selected =True
EndIf
Tip 6 - How to scroll programmatically to a row in the DataGridView
The DataGridView has a property called FirstDisplayedScrollingRowIndex that can be used in order to scroll to a row programmatically.
C#
intjumpToRow = 20;
if(dgv.Rows.Count >= jumpToRow && jumpToRow >= 1)
{
dgv.FirstDisplayedScrollingRowIndex = jumpToRow;
dgv.Rows[jumpToRow].Selected =true;
}
VB.NET
DimjumpToRowAsInteger= 20
Ifdgv.Rows.Count >= jumpToRowAndAlsojumpToRow >= 1Then
dgv.FirstDisplayedScrollingRowIndex = jumpToRow
dgv.Rows(jumpToRow).Selected =True
EndIf
Tip 7 - Calculate a column total in the DataGridView and display in a textbox
A common requirement is to calculate the total of a currency field and display it in a textbox. In the snippet below, we will be calculating the total of the ‘Freight’ field. We will then display the data in a textbox by formatting the result (observe theToString("c")) while displaying the data, which displays the culture-specific currency.
C#
privatevoidbtnTotal_Click(objectsender,EventArgse)
{
if(dgv.Rows.Count > 0)
txtTotal.Text = Total().ToString("c");
}
privatedoubleTotal()
{
doubletot = 0;
inti = 0;
for(i = 0; i < dgv.Rows.Count; i++)
{
tot = tot +Convert.ToDouble(dgv.Rows[i].Cells["Freight"].Value);
}
returntot;
}
VB.NET
PrivateSubbtnTotal_Click(ByValsenderAsObject,ByValeAsEventArgs)
Ifdgv.Rows.Count > 0Then
txtTotal.Text = Total().ToString("c")
EndIf
EndSub
PrivateFunctionTotal()AsDouble
DimtotAsDouble= 0
DimiAsInteger= 0
Fori = 0Todgv.Rows.Count - 1
tot = tot + Convert.ToDouble(dgv.Rows(i).Cells("Freight").Value)
Nexti
Returntot
EndFunction
Tip 8 - Change the Header Names in the DataGridView
If the columns being retrieved from the database do not have meaningful names, we always have the option of changing the header names as shown in this snippet:
C#
privatevoidbtnChange_Click(objectsender,EventArgse)
{
dgv.Columns[0].HeaderText ="MyHeader1";
dgv.Columns[1].HeaderText ="MyHeader2";
}
VB.NET
PrivateSubbtnChange_Click(ByValsenderAsObject,ByValeAsEventArgs)
dgv.Columns(0).HeaderText = "MyHeader1"
dgv.Columns(1).HeaderText = "MyHeader2"
EndSub
Tip 9 - Change the Color of Cells, Rows and Border in the DataGridView
C#
privatevoidbtnCellRow_Click(objectsender,EventArgse)
{
// Change ForeColor of each Cell
this.dgv.DefaultCellStyle.ForeColor =Color.Coral;
// Change back color of each row
this.dgv.RowsDefaultCellStyle.BackColor =Color.AliceBlue;
// Change GridLine Color
this.dgv.GridColor =Color.Blue;
// Change Grid Border Style
this.dgv.BorderStyle =BorderStyle.Fixed3D;
}
VB.NET
PrivateSubbtnCellRow_Click(ByValsenderAsObject,ByValeAsEventArgs)
' Change ForeColor of each Cell
Me.dgv.DefaultCellStyle.ForeColor = Color.Coral
' Change back color of each row
Me.dgv.RowsDefaultCellStyle.BackColor = Color.AliceBlue
' Change GridLine Color
Me.dgv.GridColor = Color.Blue
' Change Grid Border Style
Me.dgv.BorderStyle = BorderStyle.Fixed3D
EndSub
Tip 10 - Hide a Column in the DataGridView
If you would like to hide a column based on a certain condition, here’s a snippet for that.
C#
privatevoidbtnHide_Click(objectsender,EventArgse)
{
this.dgv.Columns["EmployeeID"].Visible =false;
}
VB.NET
PrivateSubbtnHide_Click(ByValsenderAsObject,ByValeAsEventArgs)
Me.dgv.Columns("EmployeeID").Visible =False
EndSub
Tip 11 - Handle SelectedIndexChanged of a ComboBox in the DataGridView
To handle the SelectedIndexChanged event of a DataGridViewComboBox, you need to use the DataGridView.EditingControlShowing event as shown below. You can then retrieve the selected index or the selected text of the combobox.
C#
privatevoiddataGridView1_EditingControlShowing(objectsender,DataGridViewEditingControlShowingEventArgse)
{
ComboBoxeditingComboBox = (ComboBox)e.Control;
if(editingComboBox !=null)
editingComboBox.SelectedIndexChanged +=newSystem.EventHandler(this.editingComboBox_SelectedIndexChanged);
}
privatevoideditingComboBox_SelectedIndexChanged(objectsender, System.EventArgse)
{
ComboBoxcomboBox1 = (ComboBox)sender;
// Display index
MessageBox.Show(comboBox1.SelectedIndex.ToString());
// Display value
MessageBox.Show(comboBox1.Text);
}
VB.NET
PrivateSubdataGridView1_EditingControlShowing(ByValsenderAsObject,ByValeAsDataGridViewEditingControlShowingEventArgs)
DimeditingComboBoxAsComboBox =CType(e.Control, ComboBox)
IfNoteditingComboBoxIsNothingThen
AddHandlereditingComboBox.SelectedIndexChanged,AddressOfeditingComboBox_SelectedIndexChanged
EndIf
EndSub
PrivateSubeditingComboBox_SelectedIndexChanged(ByValsenderAsObject,ByValeAsSystem.EventArgs)
DimcomboBox1AsComboBox =CType(sender, ComboBox)
' Display index
MessageBox.Show(comboBox1.SelectedIndex.ToString())
' Display value
MessageBox.Show(comboBox1.Text)
EndSub
Tip 12 - Change Color of Alternate Rows in the DataGridView
C#
privatevoidbtnAlternate_Click(objectsender,EventArgse)
{
this.dgv.RowsDefaultCellStyle.BackColor =Color.White;
this.dgv.AlternatingRowsDefaultCellStyle.BackColor =Color.Aquamarine;
}
VB.NET
PrivateSubbtnAlternate_Click(ByValsenderAsObject,ByValeAsEventArgs)
Me.dgv.RowsDefaultCellStyle.BackColor = Color.White
Me.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine
EndSub
Tip 13 - Formatting Data in the DataGridView
The DataGridView exposes properties that enable you to format data such as displaying a currency column in the culture specific currency or displaying nulls in a desired format and so on.
C#
privatevoidbtnFormat_Click(objectsender,EventArgse)
{
// display currency in culture-specific currency for
this.dgv.Columns["Freight"].DefaultCellStyle.Format ="c";
// display nulls as 'NA'
this.dgv.DefaultCellStyle.NullValue ="NA";
}
VB.NET
PrivateSubbtnFormat_Click(ByValsenderAsObject,ByValeAsEventArgs)
' display currency in culture-specific currency for
Me.dgv.Columns("Freight").DefaultCellStyle.Format = "c"
' display nulls as 'NA'
Me.dgv.DefaultCellStyle.NullValue = "NA"
EndSub
Tip 14 – Change the order of columns in the DataGridView
In order to change the order of columns, just set the DisplayIndex property of the DataGridView to the desired value. Remember that the index is zero based.
C#
privatevoidbtnReorder_Click(objectsender,EventArgse)
{
dgv.Columns["CustomerID"].DisplayIndex = 5;
dgv.Columns["OrderID"].DisplayIndex = 3;
dgv.Columns["EmployeeID"].DisplayIndex = 1;
dgv.Columns["OrderDate"].DisplayIndex = 2;
dgv.Columns["Freight"].DisplayIndex = 6;
dgv.Columns["ShipCountry"].DisplayIndex = 0;
dgv.Columns["ShipName"].DisplayIndex = 4;
}
VB.NET
PrivateSubbtnReorder_Click(ByValsenderAsObject,ByValeAsEventArgs)
dgv.Columns("CustomerID").DisplayIndex = 5
dgv.Columns("OrderID").DisplayIndex = 3
dgv.Columns("EmployeeID").DisplayIndex = 1
dgv.Columns("OrderDate").DisplayIndex = 2
dgv.Columns("Freight").DisplayIndex = 6
dgv.Columns("ShipCountry").DisplayIndex = 0
dgv.Columns("ShipName").DisplayIndex = 4
EndSub
I hope this article was useful and I thank you for viewing it.