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.
分享到:
相关推荐
Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance Host Controls in Windows Forms DataGridView Cells 继承 DataGridViewTextBoxCell 类...
WindowsFormsApplication1Datagridview上移下移 为方便C# winForm 学习爱好者而上传
测试.net remoting应用服务器时,目录下WindowsServer2/bin/Debug/WindowsServer2 应用服务器必须启动,见下图5和图6。 5、实验环境 Visual studio 2016至2019版本 C#, SQLServer 2008至2018版本 通过示例用...
The DataGridView control is the new grid control for Windows Froms 2.0. It replaces the DataGrid control with an easy to use and extremely customizable grid that supports many of the features that are...
一个DataGridView控件动态添加或删除列的例子。利用DataGridViewTextBoxColumn对象,动态给DataGridView控件动态添加列,利用DataGridView的Clear方法,删除DataGridView的行或列。
System.Windows.Forms.DataGridViewComboBoxColumn, System.Windows.Forms.DataGridViewCheckBoxColumn, DataGridView 控件提供了多个可用来调整其单元格、行和列的外观和基本行为(外观和感受)的属性。但是,...
DataGridView控件用法合集 1. DataGridView当前的单元格属性取得、变更 2. DataGridView编辑属性 3. DataGridView最下面一列新追加行非表示 4. DataGridView判断当前选中行是否为新追加的行 5. DataGridView删除行...
C# winfrom DataGridView 全选
vb.net操作DataGridView控件的用法的集合,包括: 1. DataGridView当前的单元格属性取得、变更 2. DataGridView编辑属性 3. DataGridView最下面一列新追加行非表示 4. DataGridView判断当前选中行是否为新追加的...
DataGridView属性DataGridView属性DataGridView属性DataGridView属性DataGridView属性DataGridView属性DataGridView属性DataGridView属性
datagridview
C# windows datagridview表格行上下拖动示例 一个简单的示例代码 具体可以根据需求自行修改
C#DataGridView中DataGridViewCheckBox问题
DataGridView进度条 DataGridView进度条 DataGridView进度条 DataGridView进度条 DataGridView进度条
DataGridView 使用详解DataGridView 使用详解DataGridView 使用详解DataGridView 使用详解DataGridView 使用详解
DataGridView合并单元格,合并表头
5.3.1 在Windows窗体DataGridView控件调整大小选项 39 5.3.2 Resizing with the Mouse用鼠标调整大小 42 5.3.3 Automatic Sizing自动调整大小 43 5.3.4 Programmatic Resizing编程调整大小 45 5.3.5 Customizing ...
连接数据库 dataGridView数据的显示 dataGridView定位 dataGridView修改 删除
实现了DataGridView单元格行合并和DataGridView二维表头的示例及源码
在.NET的Windows Forms数据处理应用中,经常需要处理主从表情况。例如:SQL Server 2000的Northwind数据库Custumers表和Orders表中,一个客户对应多个定单(用关系数据库理论的ER概念模型描述,客户实体与定单实体是...