????????DataGridView 控件是一個 Windows 窗體控件,它允許您自定義和編輯表格數據。它提供了許多屬性、方法和事件來自定義其外觀和行為。在本文中,我們將討論一些常見問題及其解決方案。這些問題來自各種來源,包括一些新聞組、MSDN 網站以及一些由我在 MSDN 論壇上解答的問題。
技巧 1 – 填充 DataGridView
????????在這個簡短的代碼片段中,我們將使用 LoadData() 方法填充 DataGridView。此方法使用 SqlDataAdapter 填充 DataSet。然后將 DataSet 中的“Orders”表綁定到 BindingSource 組件,這使我們能夠靈活地選擇/修改數據位置。
C#
public partial class Form1 : Form
? ? {
? ? ? ? private SqlDataAdapter da;
? ? ? ? private SqlConnection conn;
? ? ? ? BindingSource bsource = new BindingSource();
? ? ? ? DataSet ds = null;
? ? ? ? string sql;
?
? ? ? ? public Form1()
? ? ? ? {
? ? ? ? ? ? InitializeComponent();
? ? ? ? }
?
? ? ? ? private void btnLoad_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? LoadData();
? ? ? ? }
?
? ? ? ? private void LoadData()
? ? ? ? {
string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;";
? ? ? ? ? ? conn = new SqlConnection(connectionString);
sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders";
?
? ? ? ? ? ? da = new SqlDataAdapter(sql, conn);
? ? ? ? ? ? conn.Open();
? ? ? ? ? ? ds = new DataSet();
? ? ? ? ? ? SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da); ? ? ? ? ?
? ? ? ? ? ? da.Fill(ds, "Orders");
? ? ? ? ? ? bsource.DataSource = ds.Tables["Orders"];
? ? ? ? ? ? dgv.DataSource = bsource; ? ? ? ? ?
? ? ? ? }
? ? }
?? ?
VB.NET
Public Partial Class Form1
? ? ? Inherits Form
? ? ? ? ? ? Private da As SqlDataAdapter
? ? ? ? ? ? Private conn As SqlConnection
? ? ? ? ? ? Private bsource As BindingSource = New BindingSource()
? ? ? ? ? ? Private ds As DataSet = Nothing
? ? ? ? ? ? Private sql As String
?
? ? ? ? ? ? Public Sub New()
? ? ? ? ? ? ? ? ? InitializeComponent()
? ? ? ? ? ? End Sub
?
Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? LoadData()
? ? ? ? ? ? End Sub
?
? ? ? ? ? ? Private Sub LoadData()
Dim connectionString As String = "Data Source=localhost;Initial Catalog=Northwind;" & "Integrated Security=SSPI;"
? ? ? ? ? ? ? ? ? conn = New SqlConnection(connectionString)
sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," & "ShipName, ShipCountry FROM Orders"
?
? ? ? ? ? ? ? ? ? da = New SqlDataAdapter(sql, conn)
? ? ? ? ? ? ? ? ? conn.Open()
? ? ? ? ? ? ? ? ? ds = New DataSet()
Dim commandBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
? ? ? ? ? ? ? ? ? da.Fill(ds, "Orders")
? ? ? ? ? ? ? ? ? bsource.DataSource = ds.Tables("Orders")
? ? ? ? ? ? ? ? ? dgv.DataSource = bsource
? ? ? ? ? ? End Sub
End Class
技巧 2 – 更新 DataGridView 中的數據并將更改保存到數據庫中
????????編輯單元格中的數據后,如果您想在數據庫中永久更新更改,請使用以下代碼:
C#
private void btnUpdate_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? DataTable dt = ds.Tables["Orders"];
? ? ? ? ? ?this.dgv.BindingContext[dt].EndCurrentEdit();
? ? ? ? ? ? this.da.Update(dt);
? ? ? ? }
?? ??? ?
VB.NET
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? Dim dt As DataTable = ds.Tables("Orders")
? ? ? ? ? ? ? ? ? Me.dgv.BindingContext(dt).EndCurrentEdit()
? ? ? ? ? ? ? ? ? Me.da.Update(dt)
? ? ? End Sub
技巧3 – 在 DataGridView 中刪除行之前顯示確認框
????????處理 UserDeletingRow 事件,向用戶顯示確認框。如果用戶確認刪除,則刪除該行。如果用戶點擊“取消”,則設置 e.cancel = true,取消行刪除。
C#
private void dgv_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
? ? ? ? {
? ? ? ? ? ? if (!e.Row.IsNewRow)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? DialogResult res = 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
Private Sub dgv_UserDeletingRow(ByVal sender As Object, ByVal e As DataGridViewRowCancelEventArgs)
? ? ? ? ? ? ? ? ? If (Not e.Row.IsNewRow) Then
? ? ? ? ? ? ? ? ? ? ? ? Dim res As DialogResult = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
? ? ? ? ? ? ? ? ? ? ? ? If res = DialogResult.No Then
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? e.Cancel = True
? ? ? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? ? End If
End Sub
技巧 4 – 如何自動調整 DataGridView 中的列寬
????????下面的代碼片段首先自動調整列的大小以適應其內容。然后將 AutoSizeColumnsMode 設置為“DataGridViewAutoSizeColumnsMode.AllCells”枚舉值,以便在數據發生變化時自動調整列的寬度。
C#
private void btnResize_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? dgv.AutoResizeColumns();
? ? ? ? ? ? dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
?
? ? ? ? }
?? ??? ?
VB.NET
Private Sub btnResize_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? dgv.AutoResizeColumns()
? ? ? ? ? ? ? ? ? dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
?
End Sub
技巧 5 - 在 DataGridView 中選擇并突出顯示整行
C#
int rowToBeSelected = 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
Dim rowToBeSelected As Integer = 3 ' third row
If dgv.Rows.Count >= rowToBeSelected Then
? ? ? ? ?' Since index is zero based, you have to subtract 1
? ? ? ? ? ? dgv.Rows(rowToBeSelected - 1).Selected = True
End If
技巧 6 - 如何以編程方式滾動到 DataGridView 中的某一行
????????DataGridView 有一個名為 FirstDisplayedScrollingRowIndex 的屬性,可用于以編程方式滾動到某一行。
C#
int jumpToRow = 20;
if (dgv.Rows.Count >= jumpToRow && jumpToRow >= 1)
{ ? ? ? ? ? ??
? ? ? ? dgv.FirstDisplayedScrollingRowIndex = jumpToRow;
? ? ? ? dgv.Rows[jumpToRow].Selected = true;
}
?
VB.NET
Dim jumpToRow As Integer = 20
If dgv.Rows.Count >= jumpToRow AndAlso jumpToRow >= 1 Then
? ? ? ? ? ? dgv.FirstDisplayedScrollingRowIndex = jumpToRow
? ? ? ? ? ? dgv.Rows(jumpToRow).Selected = True
End If
技巧 7 - 計算 DataGridView 中的列總數并顯示在文本框中
????????一個常見的需求是計算貨幣字段的總計并將其顯示在文本框中。在下面的代碼片段中,我們將計算“運費”字段的總計。然后,我們將在顯示數據的同時,通過格式化結果(觀察ToString( "c" ) )將數據顯示在文本框中,該文本框會顯示特定于文化的貨幣。
C#
private void btnTotal_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? if(dgv.Rows.Count > 0)
? ? ? ? ? ? ?txtTotal.Text = Total().ToString("c");
? ? ? ? }
?
? ? ? ? private double Total()
? ? ? ? {
? ? ? ? ? ? double tot = 0;
? ? ? ? ? ? int i = 0;
? ? ? ? ? ? for (i = 0; i < dgv.Rows.Count; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? tot = tot + Convert.ToDouble(dgv.Rows[i].Cells["Freight"].Value);
? ? ? ? ? ? }
? ? ? ? ? ? return tot;
? ? ? ? }
?? ??? ?
VB.NET
Private Sub btnTotal_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? If dgv.Rows.Count > 0 Then
? ? ? ? ? ? ? ? ? ?txtTotal.Text = Total().ToString("c")
? ? ? ? ? ? ? ? ? End If
End Sub
?
Private Function Total() As Double
? ? ? ? ? ? ? ? ? Dim tot As Double = 0
? ? ? ? ? ? ? ? ? Dim i As Integer = 0
? ? ? ? ? ? ? ? ? For i = 0 To dgv.Rows.Count - 1
? ? ? ? ? ? ? ? ? ? ? ? tot = tot + Convert.ToDouble(dgv.Rows(i).Cells("Freight").Value)
? ? ? ? ? ? ? ? ? Next i
? ? ? ? ? ? ? ? ? Return tot
End Function
技巧 8 - 更改 DataGridView 中的標題名稱
????????如果從數據庫檢索的列沒有有意義的名稱,我們始終可以選擇更改標題名稱,如下段所示:
C#
private void btnChange_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? dgv.Columns[0].HeaderText = "MyHeader1";
? ? ? ? ? ? dgv.Columns[1].HeaderText = "MyHeader2";
? ? ? ? }
?
VB.NET
Private Sub btnChange_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? dgv.Columns(0).HeaderText = "MyHeader1"
? ? ? ? ? ? ? ? ? dgv.Columns(1).HeaderText = "MyHeader2"
End Sub
技巧 9 - 更改 DataGridView 中單元格、行和邊框的顏色
C#
private void btnCellRow_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? // 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
Private Sub btnCellRow_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? ' 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
End Sub
技巧 10 - 隱藏 DataGridView 中的列
????????如果您想根據特定條件隱藏某一列,這里有一個代碼片段。
C#
private void btnHide_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? this.dgv.Columns["EmployeeID"].Visible = false;
? ? ? ? }
VB.NET
Private Sub btnHide_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? Me.dgv.Columns("EmployeeID").Visible = False
End Sub
技巧 11 - 處理 DataGridView 中 ComboBox 的 SelectedIndexChanged
????????要處理 DataGridViewComboBox 的 SelectedIndexChanged 事件,您需要使用 DataGridView.EditingControlShowing 事件,如下所示。然后,您可以檢索組合框的選定索引或選定文本。
C#
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
? ? ? ? {
? ? ? ? ? ? ComboBox editingComboBox = (ComboBox)e.Control;
? ? ? ? ? ? if(editingComboBox != null)
? ? ? ? ? ? ? ? editingComboBox.SelectedIndexChanged += new System.EventHandler(this.editingComboBox_SelectedIndexChanged);
? ? ? ? }
?? ??? ?
private void editingComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
? ? ? ? {
? ? ? ? ? ? ComboBox comboBox1 = (ComboBox)sender;
? ? ? ? ? ? // Display index
? ? ? ? ? ? MessageBox.Show(comboBox1.SelectedIndex.ToString());
? ? ? ? ? ? // Display value
? ? ? ? ? ? MessageBox.Show(comboBox1.Text);
? ? ? ? }
VB.NET
Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
? ? ? ? ? ? ? ? ? Dim editingComboBox As ComboBox = CType(e.Control, ComboBox)
? ? ? ? ? ? ? ? ? If Not editingComboBox Is Nothing Then
? ? ? ? ? ? ? ? ? ? ? ? AddHandler editingComboBox.SelectedIndexChanged, AddressOf editingComboBox_SelectedIndexChanged
? ? ? ? ? ? ? ? ? End If
End Sub
?
Private Sub editingComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
? ? ? ? ? ? ? ? ? Dim comboBox1 As ComboBox = CType(sender, ComboBox)
? ? ? ? ? ? ? ? ? ' Display index
? ? ? ? ? ? ? ? ? MessageBox.Show(comboBox1.SelectedIndex.ToString())
? ? ? ? ? ? ? ? ? ' Display value
? ? ? ? ? ? ? ? ? MessageBox.Show(comboBox1.Text)
End Sub
技巧 12 - 更改 DataGridView 中交替行的顏色
C#
private void btnAlternate_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? this.dgv.RowsDefaultCellStyle.BackColor = Color.White;
? ? ? ? ? ? this.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine;
? ? ? ? }
VB.NET
Private Sub btnAlternate_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? Me.dgv.RowsDefaultCellStyle.BackColor = Color.White
? ? ? ? ? ? ? ? ? Me.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine
End Sub
技巧 13 - 在 DataGridView 中格式化數據
????????DataGridView 公開了一些屬性,使您能夠格式化數據,例如以特定文化的貨幣顯示貨幣列或以所需的格式顯示空值等等。
C#
private void btnFormat_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? // 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
Private Sub btnFormat_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? ' display currency in culture-specific currency for
? ? ? ? ? ? ? ? ? Me.dgv.Columns("Freight").DefaultCellStyle.Format = "c"
? ? ? ? ? ? ? ? ? ' display nulls as 'NA'
? ? ? ? ? ? ? ? ? Me.dgv.DefaultCellStyle.NullValue = "NA"
End Sub
技巧 14 – 更改 DataGridView 中的列順序
????????要更改列的順序,只需將 DataGridView 的 DisplayIndex 屬性設置為所需的值。請記住,索引從零開始。
C#
private void btnReorder_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? ?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
Private Sub btnReorder_Click(ByVal sender As Object, ByVal e As EventArgs)
? ? ? ? ? ? ? ? ? ?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
End Sub
?
我希望這篇文章對您有用,并感謝您的閱讀。
如果您喜歡此文章,請收藏、點贊、評論,謝謝,祝您快樂每一天。