DataGridView in Windows Forms – Tips, Tricks and Frequently Asked Questions(FAQ)

Posted by: Suprotim Agarwal , on 3/27/2008, in Category WinForms & WinRT
Views: 523839
Abstract: 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.
DataGridView in Windows Forms – Tips, Tricks and Frequently Asked 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 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#
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
 
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#
        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
 
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
 
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
 
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
 
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
 
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");
        }
 
        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
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#
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
 
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
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#
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
 
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#
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
Tip 12 - Change Color of Alternate Rows in the 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 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#
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
 
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#
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.
If you liked the article,  Subscribe to my RSS Feed

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by sin on Friday, March 28, 2008 6:53 AM
Very interesting FAQ thank's a lot
Comment posted by Fernando on Sunday, March 30, 2008 2:17 AM
Excellent post! This is what I was looking for right now. Thanks.
Comment posted by Chetan on Saturday, April 5, 2008 7:47 AM
well the article is pretty good! though i have some problems with it.
when i say dataset = null; // says cannot be null

also
DataTable dt = set.Tables["newtable"];
            this.dataGridView1.BindingContext[dt].EndCurrentEdit();
            this.dp.Update(dt);// line gives me Syntax error in Update statement!.
help me pleasee!!
Comment posted by ajit jha on Tuesday, April 8, 2008 9:02 PM
those tips were useful thanks
Comment posted by Santhanaprabu on Wednesday, April 16, 2008 7:17 AM
I fully satisfied because for windows application with which article has covered lot of things.
we are expecting more functions like datgrid controls with textbox combobox and all some more xample
Comment posted by vishlal on Thursday, April 24, 2008 6:38 AM
This article is very useful I have learnt  more abt Datagridview control.
Thanks a Lot
Comment posted by Jothi Natarajan on Tuesday, April 29, 2008 2:25 PM
Thanks for the code
Its very useful
Comment posted by Elmira on Sunday, May 4, 2008 9:21 AM
Thanks for the code! Simple and clear! I like such examples.
Comment posted by sivakumaran on Wednesday, May 14, 2008 7:20 AM
Nice one. I learned a lot from it. But, can you pls say, how to give style in Row Header.
Comment posted by Suprotim Agarwal on Wednesday, May 14, 2008 12:23 PM
Thanks everyone for their comments.

Siva: Check if this helps

http://msdn2.microsoft.com/en-us/system.windows.forms.datagridview.columnheadersdefaultcellstyle.aspx

Set EnableHeadersVisualStyles to false.
Comment posted by Joe Coder on Thursday, June 12, 2008 12:35 PM
re: Tip 7 - Calculate a column total in the DataGridView and display in a textbox

If your datagridview is attached to a datatable, try using DataTable.Compute() instead.

http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx
Comment posted by Venkatesan on Tuesday, June 17, 2008 4:07 AM
Nice one. I learn lot from this list. But, Can u tell me how to set checkbox in selected column.
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 11:53 AM
Thanks Joe.
Venkatesan: Do you mean to add a checkbox at runtime or enable the checked state?
Comment posted by Fahim on Tuesday, June 24, 2008 2:10 AM
it really very good post...but i have problem in data grid is that i have one datagrid for entering data in datagrid have one product table and bonus table....well in datagrid there are four colum first is product code then product name then bonus amount thyese all data will be save in bonus table....but the data productcode must be from product table in combogrid control when user select product code from datagridcombobox then product name will automatically show the data according to seleced index change....plz kindly help me
Comment posted by Gregory Fequiere on Monday, June 30, 2008 1:31 AM
Very interesting Article. Thanks Chief.
Comment posted by Ashish Tewari on Tuesday, July 8, 2008 7:14 AM
It's very nice.
Comment posted by Nithya on Monday, July 14, 2008 6:51 AM
Hi, but pls can u help in formatting "ROW HEADER"?..
so far available help is for Column styling..
thanks in advance..

Nithya
Comment posted by Nithya on Tuesday, July 15, 2008 7:02 AM
Hi,
I found the answer, it can be like
gridview1.RowHeadersWidth = 100 //set the rowheader width
gridview1.Rows(Index).HeaderCell.Value = "Row Header"// specify the index of row and its value..

thanks n regards
Nithya


Comment posted by Suprotim Agarwal on Wednesday, July 16, 2008 1:47 PM
Nithya: Good going!!
Comment posted by vasanthiraajan on Tuesday, July 22, 2008 9:09 AM
hi,

this is very useful to me..

Thank u..

keep it up...
Comment posted by Ram on Thursday, July 24, 2008 11:41 PM
really this is nice article for beginner.
Comment posted by rewR on Tuesday, August 5, 2008 6:06 AM
dfdfd
Comment posted by Anish M N on Monday, August 11, 2008 8:04 AM
Hi

Excellent aricle
soluions for a lot of questions in a single page

Thanks a lot
Anish.M.N
Cochin
Comment posted by Ajit Kumar Thakur on Friday, August 15, 2008 5:39 AM
Hi
Really Knowledgeble article but one thing also
attached with it is attaching datagrid to controls like checkbox etc.


Ajit Kumar Thakur
Software Developer
New Delhi
Comment posted by Shlomo on Thursday, August 21, 2008 12:02 PM
great article thanks was a great help
Comment posted by Christian on Sunday, August 24, 2008 12:16 PM
nice post.. but syntax error on UPDATE (c#)
Comment posted by Suprotim Agarwal on Tuesday, August 26, 2008 5:16 AM
What is the error you get? Are you talking about Tip 2?
Comment posted by Jorge Diaz Tambley on Friday, September 5, 2008 11:46 AM
Thank you very much... quite useful indeed

regards from Santiago, Chile
Comment posted by Jitendra on Monday, September 8, 2008 11:35 PM
very very Useful...
Thanks a lot!!
Can u provide These type of Articles on Other Control Also
Comment posted by Suprotim Agarwal on Tuesday, September 9, 2008 9:32 PM
Jitendra: You can find such similar articles over here
http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=47

check out all the pages.
Comment posted by Jitendra on Tuesday, September 9, 2008 10:38 PM
ya Suprotim ...
I Have Checked it...
These are Really Helpful..
Thanks For That
Comment posted by ichbinvinh on Monday, September 15, 2008 9:09 AM
tip 2: i got an error.

private void btnUpdate_Click(object sender, EventArgs e)
        {
            DataTable dt = ds.Tables["Orders"];
           this.dgv.BindingContext[dt].EndCurrentEdit();
            this.da.Update(dt);
        }
--------> Error, please help!
"Update requires a valid UpdateCommand when passed DataRow collection with modified rows"
Comment posted by Suprotim Agarwal on Tuesday, September 16, 2008 8:56 AM
ichbinvinh: By any means are you using a TableAdapter. Can you put a try catch block and give more details about the exception?
Comment posted by nikhil tripathi on Thursday, September 25, 2008 12:46 AM
Hi
Really Knowledgeble article but one thing also
attached with it is attaching gridview to controls like checkbox etc,
and also how to use validation control in gridview at the time of updation.


Nikhil Tripathi
Software Developer
Vallabh Vidhyanagar,
Anand,Gujarat
Comment posted by varun on Tuesday, September 30, 2008 6:53 AM
I have a grid with checkboxes attached to it . Now I want as soon as any user click on any of the checkbox from grid I have to count how many checkboxes are checked . ike first time it will be one and if user checked another it will be two. Now if user deselects the first checkbox then the value should be again 1.
Comment posted by ARIF on Tuesday, October 21, 2008 5:40 PM
Nice Post,
I'll b very happy, if someone can provide any link of tutorial about two columns with single header.
Operationally, two columns must have two column headers but what I need a common header just above these two headers. Common header works only on outlook.
Such As  Common Header     Employee
          1st column header ID
          2nd column header SALARY
It will be a pretty nice work.
Thanks Coders

"CODE TO LEARN CODE"
Comment posted by Suprotim Agarwal on Wednesday, October 22, 2008 12:09 PM
I do not think the DGV has that feature!
Comment posted by nayaz on Wednesday, November 5, 2008 6:08 AM
Thank you very much....
This page contain lot of useful information...
Comment posted by manigandan on Friday, November 21, 2008 7:36 AM
super

this is very useful to me..

   mani
   coimbatore
Comment posted by Sathish on Monday, January 5, 2009 10:10 AM
good
it is very useful to beginners..
I need the code for delete a selected row from datagridview in VB.NET

Anyone can help me.
Thanks in advance..
Comment posted by srajmohan on Wednesday, January 7, 2009 8:16 AM
nice very useful thank you
Comment posted by Rajesh on Monday, January 12, 2009 6:42 AM
very nice post.. i need a code to check the status of the chkbox column in dgv
Comment posted by Karun on Wednesday, February 4, 2009 11:37 AM
really nice post.....
this is how you can delete selected rows from datagridview

Private Sub btndel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndel.Click
        If dgv.Rows.Count = 1 Then
            MessageBox.Show("Not allowed to delete this row.", "Not Allowed", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            Exit Sub
        End If
        Dim res As Integer = MessageBox.Show("Are you sure you want to delete this row?", "Delete Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
        If res = vbYes Then
            If Not dgv.CurrentRow.IsNewRow Then
                dgv.Rows.Remove(dgv.CurrentRow)
            End If
        End If
End Sub
Comment posted by Suprotim Agarwal on Friday, February 6, 2009 2:32 AM
Karun: I haven't tested it but it seems it shld work. Thanks for the code.
Comment posted by Georges on Sunday, February 8, 2009 9:07 AM
hi nice tips ,
how can add validation and event for each column like keypress
thanks in advance
Comment posted by Joshua Sands on Thursday, March 12, 2009 2:09 PM
Excellent FAQ; thanks for posting it.

You might addd that SQL Server tables must have a PRIMARY KEY CONSTRAINT defined on them and that data must be part of the dataset. Simply declaring an ID column as IDENTITY is not good enough.
Comment posted by Suprotim Agarwal on Sunday, March 15, 2009 1:59 AM
Joshua: Thanks for mentioning that explicitly.
Comment posted by Karun on Thursday, April 23, 2009 7:57 AM
Hello
how can set the format of any particular column? for e.g i want to set the format as number of any column of the datagridview
Comment posted by Mohan Goud on Saturday, May 2, 2009 6:07 AM
Hello sir ,
Excellent article
It will be a pretty nice work.
Thanks Coders
Comment posted by Madix_t on Saturday, May 9, 2009 12:45 AM
no comment yet
Comment posted by manoj dhanik on Friday, June 19, 2009 8:55 AM
awesome article ....
Comment posted by tsgiannis on Monday, August 3, 2009 7:18 AM
Nice Article.I am experimenting right now with datagridview and in a couple of minutes of reading  i have a complete "professional" look.Thanks.
Comment posted by raman on Tuesday, September 29, 2009 7:39 AM
Its Very nice article.It's Very helpful for me and beginers also.

Thanks & Regards,
Ramana.
Comment posted by WJ on Sunday, December 6, 2009 2:14 PM
Data Grid
Comment posted by Harvey on Wednesday, December 30, 2009 7:37 AM
I need Some serious help!

I've been stuck on this coding for weeks not knowing the correct code for a Save function once a value has been entered into the datagrid on the running form...

Pleasee could someone help me solve this problem..
Much appreciated!

Harvey

The Code which i have is shown below... Sorry for the mess... i have tried various ways and many times...

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click'Purpose: When Save button is clicked: Follow the following procedures: Enable visibility of all buttons and Data Grid on form

Dim i As Integer
Dim j As Integer
row = DataGridView1.Rows(i)
For i = 0 To DataGridView1.Rows.Count - 1
Dim row As DataGridViewRow
For j = 1 To row.Cells.Count - 1
'MsgBox(DataGridView1.Rows(i).Cells(r).ToString)
Next
Next

'Clear the table in the data set ready
StockDataSet1.Tables("tblStock").Clear()'Add a new record to the table

'StockDataSet1.Tables("tblStock").Rows.Add("Nothing", Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)

'Creating and setting the Current Row Number
currentrowno = 0

'Update the table in the database so the stock gets allocated by SQL Server StockAdapter.Update (StockDataSet1, "tblStock")'Create query to retrieve required records/fields

StockAdapter.SelectCommand.CommandText = "SELECT * FROM tblStock" StockAdapter.TableMappings.Add("tblStock", "tblStock")'Empty the table in the data set

StockDataSet1.Tables("tblStock").Clear()'Execute the Sql Command to fill the table in the Data Set

StockAdapter.Fill(StockDataSet1, "tblStock")'Purpose: Save the changes made to the Customer record on the screen

'Copy the data from the screen into the Data Set
'Creating and setting the Current Row Number

currentrowno = 0

If StockDataSet1.HasChanges() Then  

Dim StockAdapter As SqlDataAdapterDim sqlcmdbldStock As SqlCommandBuilder' Create the DataAdapter.
StockAdapter = StockAdapter.SelectCommand.CommandText = New SqlDataAdapter"SELECT * FROM tblStock"

' Map Table to Contacts.
StockAdapter.TableMappings.Add("tblStock")' Make the CommandBuilder generate the

' insert, update, and delete commands.
sqlcmdbldStock = SqlCommandBuilder(StockAdapter)StockAdapter.TableMappings.Add(New _"tblStock", "PackSize5s")' Uncomment this code to see the INSERT, UPDATE, and DELETE commands.
Debug.WriteLine(Debug.WriteLine(sqlcmdbldStock.GetInsertCommand.CommandText)
Debug.WriteLine(Debug.WriteLine(sqlcmdbldStock.GetUpdateCommand.CommandText)
Debug.WriteLine(Debug.WriteLine(sqlcmdbldStock.GetDeleteCommand.CommandText)"*** INSERT ***")"*** UPDATE ***")"*** DELETE ***")' Save the changes.
StockAdapter.Update(StockDataSet1, "tblStock")

'StockDataSet1.Tables("tblStock").Rows(currentrowno)("ItemName") = ItemNameDataGridViewTextBoxColumn.DataGridView.Rows().Item(i).Cells().Count.ToString
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize5s") = PackSize5sDataGridViewTextBoxColumn.DataGridView.Rows().Item(i).Cells().ToString
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize10") = PackSize10DataGridViewTextBoxColumn.DataGridView.Rows().Item(i).Cells().ToString
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize20") = PackSize20DataGridViewTextBoxColumn.DataGridView.Rows().Item(i).Cells().Count.ToString
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize24s") = PackSize24sDataGridViewTextBoxColumn.DataGridView.Item(4, 4)
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSizeSmall") = PackSizeSmallDataGridViewTextBoxColumn.DataGridView.Item(5, 5)
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSizeKing") = PackSizeKingDataGridViewTextBoxColumn.Index
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize12.5g") = PackSize125gDataGridViewTextBoxColumn.Index 'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize25g") = PackSize25gDataGridViewTextBoxColumn.Index
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("PackSize50g") = PackSize50gDataGridViewTextBoxColumn.Index
'StockDataSet1.Tables("tblStock").Rows(currentrowno)("ItemCode") = ItemCodeDataGridViewTextBoxColumn.ToString 'StockAdapter.Update(StockDataSet1, "tblStock")

End If

MessageBox.Show()"The updates have been saved to disk.", "Save Updates", MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

Please let me know if you can help or have any suggestions!
Thanks..
Comment posted by Admin on Friday, January 1, 2010 1:48 AM
Harvey: Please post your question over here

http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/threads
Comment posted by Harvey on Friday, January 1, 2010 10:14 AM
Thank you Admin
Comment posted by jayesh on Monday, January 11, 2010 5:38 AM
with this code how i perform delete record ... record is deleted but it reside in database. any solution
Comment posted by Sarathy on Monday, January 25, 2010 2:36 PM
Thanks a lot
Comment posted by Seminyak Villas on Tuesday, February 9, 2010 5:45 PM
How to show data in datagridview with looping.
i want to show data from database to datagridview. but i dont want to use datasource/dataset and i want to show the data using a looping methode. could you help me, please....

---
Adi
http://baliseminyakvillasrental.com
http://balivillasinformation.com
Comment posted by nagaraju on Sunday, March 21, 2010 9:17 AM
how to print the selected rows of datagridview data in vb.net windows forms applications. please send immediately, i need urgently, this is one task in my project. so please help me.
Comment posted by Suprotim Agarwal on Monday, March 22, 2010 11:04 PM
You can export the grid to excel and then print it from there.

If you want a DGV solution only, these two links should be useful:
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/dc9d3acf-ccf8-457f-ba31-ef09fb357aee
http://www.codeproject.com/KB/grid/PrintDataGridView.aspx
Comment posted by Mouli on Wednesday, April 21, 2010 7:02 AM
Hi.. Thanks for your coding.. It really helps a lot. Actually I'm inserting one datagridview in windows application form. While running that program I will insert datas manually in datagridview. Suppose if the entering datas are large in any of the specific column then we cant enter as vertically in any of the cell. My question is, After pressing ALT + ENTER in specific column, then cell size should get increased in datagridview (Like we do in Microsoft Excel sheet).
Comment posted by Benodh on Sunday, June 13, 2010 2:25 AM
i cannot update the database using this code. whenever i try to update the datagridview i get the following message. "Invalid operation was unhandled: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.". i have used mssql server.
Please find the solution quickly
Comment posted by swetha Basavaraj on Tuesday, June 15, 2010 1:55 AM
Hi,
Information is very useful for every one working on windows application.These are very basic for any new application.
Thanku.
Comment posted by Parth mehta on Sunday, July 11, 2010 7:32 AM
hi, i have one question i want to fill combobox , by inserting values in datagridview's cell how can i do it can you help me ?? or please check it as soon as possible bcoz my exams are near so please help me ..
some one said me that you can write like combobox1.items.add(datagridview1.selectedcell.add) is this true or false pleas send me the right method please
Comment posted by jhello on Wednesday, August 18, 2010 12:49 PM
how about updating and deleting in inner joined tables??
Comment posted by Jai Singh on Thursday, December 9, 2010 4:48 PM
Hi Sir, I am Jai. I am M.TECH(CS). This is code is very useful for programmers. Thanks a lot sir.
Comment posted by kalla on Monday, February 21, 2011 4:03 AM
how to add a user control to a cell in a DataGridView.
Comment posted by kavitha Raveenthiran on Wednesday, March 16, 2011 4:15 AM
Really very useful for beginners.Great Job!
Comment posted by Nitin Murali on Saturday, March 26, 2011 12:28 AM
It Worked! thanks a lot! :)
Comment posted by Nidhi Shah on Monday, April 4, 2011 1:12 AM
How can i open a child window on Data Grid View in C# using Windows Application???

please help me.
Comment posted by Surbhi on Tuesday, April 5, 2011 5:06 AM
I want to add check box to every row in the data grid view and the specific column of the specific row will be displayed in the text box.specific row will be selected by checking the check box.At a time one check box can be selected;otherwise displays warning to check one row.

please help me.I need it urgently.
Comment posted by 54 on Thursday, May 19, 2011 10:26 PM
fgdfgdfg
Comment posted by sampriya paul on Wednesday, June 22, 2011 1:09 AM
All these code are really very helpful.
Thanks.

Comment posted by Avik Banerjee on Tuesday, August 9, 2011 9:18 AM
Lovely Explanation Suprotim.A great comiplation of most widely used operations on a DGV.Thanks a Ton.Keep it up.
Comment posted by atz on Wednesday, September 7, 2011 9:33 AM
thank your for posting this tutorial... it helps me a lot... :)
Comment posted by xcvx on Wednesday, October 12, 2011 7:13 AM
sfsdf
Comment posted by Matthew Coffin on Monday, November 7, 2011 8:29 AM
Tip 11 - Selected Index Change
I have a datagridview - linked to data source. I have one column defined as a combo box. I have added your code. The issue I have is when I press the arrow on the combo box the first time, it works. However, when I select the next row to change it's value in column 11 (my combo box column) the event fires 3 times, showing
   selected index -1 , combo.text is ""
next it shows
   selected index (0,1 oe 2), depending upon what i selected in the previous edit. Can you help please
   selcted index 1, combo text is WindowsApplication1.mmtypevalues ¿?
then it shows



I Create the combo box as written below

   Private Sub Form_Errors_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.My_RegisterTableAdapter.Fill(Me.MyMonitorDataSet.My_Register)
        Dim mmtypes As New ArrayList
        Dim tboxcbo1 As New ArrayList
        Dim miboxcolumn As DataGridViewComboBoxColumn = Me.My_RegisterDataGridView.Columns(11)
        mmtypes.Add(New mmtypevalues(0, "Unkown"))
        mmtypes.Add(New mmtypevalues(1, "Accept"))
        mmtypes.Add(New mmtypevalues(2, "Reject"))
        tboxcbo1.Add(New mmtypevalues(0, "Todos"))
        tboxcbo1.Add(New mmtypevalues(1, "Unkown"))
        tboxcbo1.Add(New mmtypevalues(2, "Accept"))
        tboxcbo1.Add(New mmtypevalues(3, "Reject"))

        miboxcolumn.DataSource = mmtypes
        miboxcolumn.ValueMember = "Value"
        miboxcolumn.DisplayMember = "Display"
        With ToolStripComboBox1.ComboBox
            .BindingContext = Me.BindingContext
            .ValueMember = "Value"
            .DisplayMember = "Display"
            .DataSource = tboxcbo1
        End With

        My_RegisterBindingSource.Sort = "idx"

    End Sub
Comment posted by Matthew Coffin on Monday, November 7, 2011 8:33 AM
Tip 11 - Selected Index Change (posted again, because the first posy became corrupt)
I have a datagridview - linked to data source. I have one column defined as a combo box. I have added your code. The issue I have is when I press the arrow on the combo box the first time, it works. However, when I select the next row to change it's value in column 11 (my combo box column) the event fires 3 times, showing
   selected index -1 , combo.text is ""
then it shows

  selcted index 1, combo text is WindowsApplication1.mmtypevalues ¿?

and finally it shows

   selected index (0,1 oe 2), depending upon what i selected in the previous edit.

Can you help please



I Create the combo box as written below

   Private Sub Form_Errors_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.My_RegisterTableAdapter.Fill(Me.MyMonitorDataSet.My_Register)
        Dim mmtypes As New ArrayList
        Dim tboxcbo1 As New ArrayList
        Dim miboxcolumn As DataGridViewComboBoxColumn = Me.My_RegisterDataGridView.Columns(11)
        mmtypes.Add(New mmtypevalues(0, "Unkown"))
        mmtypes.Add(New mmtypevalues(1, "Accept"))
        mmtypes.Add(New mmtypevalues(2, "Reject"))
        tboxcbo1.Add(New mmtypevalues(0, "Todos"))
        tboxcbo1.Add(New mmtypevalues(1, "Unkown"))
        tboxcbo1.Add(New mmtypevalues(2, "Accept"))
        tboxcbo1.Add(New mmtypevalues(3, "Reject"))

        miboxcolumn.DataSource = mmtypes
        miboxcolumn.ValueMember = "Value"
        miboxcolumn.DisplayMember = "Display"
        With ToolStripComboBox1.ComboBox
            .BindingContext = Me.BindingContext
            .ValueMember = "Value"
            .DisplayMember = "Display"
            .DataSource = tboxcbo1
        End With

        My_RegisterBindingSource.Sort = "idx"

    End Sub  
Comment posted by yogesh yadav on Friday, December 9, 2011 2:20 PM
Hi Everyone,

can anybody give the more learning eg. of window application using C#
Comment posted by vignesh prabu on Thursday, December 22, 2011 3:50 AM
Nice explanations..
Comment posted by Ashish on Tuesday, January 10, 2012 6:07 AM
thanks a lot,i want to do update and search in dataGridView
Comment posted by azharuddin on Tuesday, January 10, 2012 7:56 AM
can anybody give the more learning eg. of window application using C#
Comment posted by muhammed ashfaq on Friday, January 13, 2012 4:37 AM
thanks brother....:-)
Comment posted by Tanvir on Friday, January 20, 2012 12:05 AM
Nice one
5 *
Comment posted by Gleams on Thursday, February 2, 2012 1:50 PM
A useful datagridview link

http://csharp.net-informations.com/datagridview/csharp-datagridview-tutorial.htm

glm.
Comment posted by harmeet singh on Tuesday, February 14, 2012 3:10 AM
hi, i am binding the data in datagrid but i want to show selected column in data grid.
but when i double click on the data grid  i want that all data should bind into tools on page. Please Help me.
Comment posted by veeramani on Wednesday, February 22, 2012 4:14 AM
very good. It is very useful for beginners
Comment posted by minsara on Sunday, February 26, 2012 12:06 PM
tnxxxxx alot for making my life easy. nice post
Comment posted by ahd on Thursday, March 1, 2012 4:47 AM
very useful article
thanks
can you provide how to add rows in datagridview at runtime, please mail me
thanks in advance
Comment posted by mukesh kumar on Thursday, June 21, 2012 2:51 AM
Dear sir my query is i am develop a desktop application in vb.net so i am asking a simple question if web site is access on-line any where any time but desktop application is not access online why .sir please give me answered like desktop applcation  in Team viewer so its a desktop application i m very 2 need the save data ,delete data ,modefiy data,so evey thing access the data in desktop applcation in a central data base so please give me answered sir.


thanks and regards
mukesh kumar  
Comment posted by dhey on Tuesday, October 16, 2012 7:01 AM
nice... very useful article....
Comment posted by Dinesh on Thursday, November 1, 2012 2:54 AM
The code snippets were really helpful. Thanks !!
Comment posted by Roger on Saturday, November 10, 2012 11:01 AM
This is one of the best sites I've found on DatGridViews!
I am very grateful for you and your work.
Thanks Rog
Comment posted by Jithener on Wednesday, November 21, 2012 3:21 AM
niceeeeeeeeeee
Comment posted by Jithener on Wednesday, November 21, 2012 3:21 AM
niceeeeeeeeeee
Comment posted by mayank jain on Tuesday, January 8, 2013 1:31 AM
wow u did a grate job. keep posting.
Comment posted by dami on Sunday, January 20, 2013 2:24 PM
sir can u tell me how to delet enitre row of datagridview by single click on any cell of row
Comment posted by aravind on Friday, July 19, 2013 1:22 AM
Superb Excellent About the Data Grid view . :)
Comment posted by dharmendra sharma on Tuesday, November 12, 2013 1:37 AM
dear sir,
i am create a destop application in c# and i want to add a button in datagridview and click the button jump to next form.and how to createa pdf file in datagridview,,,,\plz , sir suggest me.....thnks in advance
Comment posted by Nafees on Monday, December 30, 2013 3:55 AM
its really informative. I learned a lot. thanks
Comment posted by ishwar Kumar on Thursday, January 9, 2014 4:57 AM
Sir i am begineer in windows form programing so please tell me that how can i fetch datagridview data in any text box at any time
Comment posted by SunandSingh on Tuesday, January 14, 2014 9:11 AM
Good work
Comment posted by bhanu.siripuram on Thursday, February 13, 2014 4:04 AM
nice explanation
Comment posted by Donica on Friday, May 23, 2014 5:54 AM
How to transact a transaction if you're customer is paid . What is the code? for that in vb.net
Comment posted by v k sharma on Friday, July 4, 2014 3:15 AM
Thanks for providing such an informational  blog.
thanks
Comment posted by sarathkumar on Wednesday, August 27, 2014 5:07 AM
Thanks for your notes to very helpful
Comment posted by ej on Saturday, September 6, 2014 9:29 AM
Could you give an example on how to perform a sarch in several gridview controls with input from one single text box.

Example :

I have 3 different customer tables, I create 3 griedviews one for each of them.

I have one textbox for input of name to search  for ,
when I type the name in the textbox ...I would like to filter the 3 separate gridviews with the searchresult  in each of them at the same time..... so I only need to punch the serach criteria once ....






Comment posted by wahyu on Tuesday, December 9, 2014 10:24 AM
Thank you for articel
Comment posted by Sharmila Sonavane on Tuesday, February 17, 2015 9:10 AM
Thanks lot ... It helps me lot...