Data Grid View in Windows Forms
Data Grid View in Windows Forms
Questions(FAQ)
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 2 Update the data in the DataGridView and save changes in the database / Aktualizacji
danych w DataGridView i zapisa zmiany w bazie danych/
After editing the data in the cells, if you would like to update the changes permanently in the database, use the
following code:
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
Tip 3 Display a confirmation box before deleting a row in the DataGridView / Wywietli okno
potwierdzenia przed usuniciem wiersza w 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#
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
Tip 4 How to autoresize column width in the DataGridView /Jak automatycznie dopasowa
szeroko kolumny w 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#
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
Tip 5 - Select and Highlight an entire row in DataGridView /Wybierz i zaznacz cay wiersz w
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
Tip 6 - How to scroll programmatically to a row in the DataGridView / Jak programowo przewin
do zadanego wiersza w DataGridView /
The DataGridView has a property called FirstDisplayedScrollingRowIndex that can be used in order to scroll to a
row programmatically.
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
Tip 7 - Calculate a column total in the DataGridView and display in a textbox / Obliczy czn
kolumny w DataGridView i wywietla w polu tekstowym /
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 the ToString("c")) while displaying the data, which displays the culture-specific
currency.
C#
Tip 8 - Change the Header Names in the DataGridView /Zmiana nazw nagwkw w 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#
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
Tip 9 - Change the Color of Cells, Rows and Border in the DataGridView / Zmie kolor komrek,
wierszy i Granicznej w 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
Tip 12 - Change Color of Alternate Rows in the DataGridView /Zmie kolor co drugiego wiersza w
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
Tip 14 Change the order of columns in the DataGridView /Zmieni kolejno kolumn w
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#
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
I hope this article was useful and I thank you for viewing it.