How to programmically add multiple rows to datagridview

dave_sky
dave_sky used Ask the Experts™
on
I need sample code to programmically add a predeterminded number of rows to a bound datagridview with a click event.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dirk HaestProject manager

Commented:
Did you already succeed to add 1 row ?
Did you try:
Datagridview.rows.add("","","","")
(add all the parameters as an empty string, 0, ... (default values)

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

Author

Commented:
Dhaest,

>>Did you already succeed to add 1 row ?
Yes.

I get this error message when I use the sample code from ms:
Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
Hello Dhaest
If you have a data bound DataGridView, then you have probably a tableAdapter. I think you can add rows throug the tableAdaptor, and the Tableadaptor updates the dataGridView
Project manager
Commented:
Rows cannot be added programatically to the datagridview's collection when control is databound
Solution: To add a row to a databound DataGridView, add the row to the underlying data source (e.g., DataTable or BindingSource).

Example below

DataRow dr;
DataSet ds; // this is bound to DataGridView
 
// some logic setting up dataset and tables within
 
dr = ds.Tables[0].NewRow(); // Table[0] of ds is the data I want to display
dr["Column1"] = "Finally";
dr["Column2"] = "Got";
dr["Column3"] = "this";
dr["Column4"] = "Working";
 
// add row to dataset now
ds.Tables[0].Rows.Add(dr);

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial