You are on page 1of 8

c 

 
  Ê
ÊÊ
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#Ê

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Ê
ÊÊ

c 


 

      


 Ê
ÊÊ
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Ê
c      
 
  


  Ê
ÊÊ
Xandle 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Ê

c  !
 
 "  
 

  Ê
ÊÊ
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Ê
Ê

c #$%
 !  
 
 
  Ê
ÊÊ
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Ê

c &$!
  
 
  

  Ê
ÊÊ
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Ê
ÊÊ
c '$( 
  

 

       


Ê
ÊÊ
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#Ê

private void btnTotal_Click(object sender, EventArgs e)Ê



if(dgv.Rows.Count > 0)Ê
txtTotal.Text = Total().ToString("c");Ê

ÊÊ
c )$( 
! *  

  Ê
ÊÊ
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Ê
ÊÊ

c +$( 
((,- . 

  Ê
ÊÊ
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Ê

c /$!  (  



  Ê
ÊÊ
If you would like to hide a column based on a certain condition, here¶s a snippet for that.Ê

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Ê
ÊÊ

c $! %
0 (  (. 

  Ê
ÊÊ
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#Ê

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Ê

c $( (1

- 

  Ê
ÊÊ
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Ê
ÊÊ

c $2


 

  Ê
ÊÊ
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#Ê

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Ê
ÊÊ

c  ( 
  

  Ê
ÊÊ
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. Ê

You might also like