Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I Have form 1 with 4 textboxes and 1 button, and I have form 2 which contains dataGridView, I want to add new row to the datagridview from the other form.

but it give me this error:
SQL
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index




This is my code on the Button Click.

C#
Main frm = new Main();

frm.dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
frm.dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
frm.dataGridView1.Rows[0].Cells[2].Value = textBox4.Text;
frm.dataGridView1.Rows[0].Cells[3].Value = dateTimePicker1.Value;
frm.dataGridView1.Rows.Add();
this.Hide();
frm.Show();
Posted
Updated 30-Oct-15 12:55pm
v2
Comments
George Jonsson 30-Oct-15 19:35pm    
Do you have any rows in the DataGridView?
How many columns do you have in the DataGridView.
R.M49 31-Oct-15 3:57am    
Yes I have rows because the DataGridView is filled by DataSet.
there are 4 columns

1 solution

Hi, Add Columns in your datagridview, because without defining columns you can't assign data to datagridview, so create columns in datagridview, and use the following line to add rows to datagridview.

C#
frm.dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox4.Text, dateTimePicker1.Value);
 
Share this answer
 
Comments
R.M49 31-Oct-15 4:01am    
There are 4 columns, the DataGridView is filled by DataSet.
How can I define them.
VR Karthikeyan 31-Oct-15 4:52am    
In case you are using DataSet to fill datagridview, its very simple to add a new row to it. Refer the below code.

DataRow objNewRow = YourDataSet.Tables[YourTableIndex].NewRow();
objNewRow[0] = textBox1.Text;
objNewRow[1] = textBox2.Text;
objNewRow[2] = textBox4.Text;
objNewRow[3] = dateTimePicker1.Value;
YourDataSet.Tables[YourTableIndex].Rows.Add(objNewRow);
YourDataSet.Tables[YourTableIndex].AcceptChanges();
R.M49 31-Oct-15 5:01am    
DataRow obj = ds.Tables[0].NewRow();
obj[0] = textBox1.Text;
obj[1] = textBox2.Text;
obj[2] = textBox4.Text;
obj[3] = dateTimePicker1.Value;
ds.Tables[0].Rows.Add(obj);
ds.Tables[0].AcceptChanges();


I use this code, now it doesn't give me any error, the form of datagridview is shown but the row doesn't be added and nothing changed in the DGV
VR Karthikeyan 31-Oct-15 5:12am    
After adding new row to the table,
Reassign datasource of datagridview with new table with new row, like,
dataGridView.DataSource = null;
dataGridView.DataSource = ds.Tables[0];
R.M49 31-Oct-15 5:35am    
thaaaaaaaanks alooot, that is work, but the problem now when I add the new row it open a form that contain only this row, how can make this row be added under the all rows ??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900