Monday, April 18, 2011

Adding new row to DataGridView programatically in C#

This article would be helpful if you are looking to add rows programatically to DataGridView and keeping key values invisible to user.

Heres a simple relation between ASP.Net & WinForms.

ASP.Net <--> WinForms
GridView <--> DataGridView
DataKeyNames(Considering 1 column is stored) <---> DataGridViewRow.Tag(Tag can store literally any value, but here it can solve our problem)

With the below code you have control on what you display to users while you still keep (one)important detail invisible.
Only one solution, to lengths of my knowledge, will help in this situation. Using DataGridViewRow.

List custList = GetAllCustomers();

            foreach (Customer cust in custList)
                //First add the row, cos this is how it works! Dont know why!
                DataGridViewRow R = dataGridView1.Rows[dataGridView1.Rows.Add()];
                //Then edit it
                R.Cells["Name"].Value = cust.Name;
                R.Cells["Address"].Value = cust.Address;
                R.Cells["Phone"].Value = cust.PhoneNo;
                //Customer Id is invisible but still usable, like, 
                //when double clicked to show full details
                R.Tag = cust.IntCustomerId;

No comments:

Post a Comment