Reputation: 511
I want to use datagridview for show some data(information) to user. My datagridview has 4 column. When I use this code
private void sfactor_Load(object sender, EventArgs e)
{
dataGridView1.Rows[0].Cells[0].Value = "book";
dataGridView1.Rows[1].Cells[0].Value = "pen";
dataGridView1.Rows[2].Cells[0].Value = "x";
dataGridView1.Rows[3].Cells[0].Value = "y";
dataGridView1.Rows[4].Cells[0].Value = "z";
}
I want to show this info just in column[0]
. When program run, it has exception:
Index was out of range.
Must be non-negative and less than the size of the collection.
Parameter name: index
I know why but I don't know how I can solve it. Now I need your help and your experience. I wait for your answer.
Upvotes: 1
Views: 795
Reputation: 73303
You need to create the rows before assigning values. There's an overload which lets you create and set values at the same time:
dataGridView1.Rows.Add("book");
dataGridView1.Rows.Add("pen");
dataGridView1.Rows.Add("x");
dataGridView1.Rows.Add("y");
dataGridView1.Rows.Add("z");
Upvotes: 1
Reputation: 17964
You want to create a datatable and fill that up.
Then you can use the datasource property of your datagridview to bind your datatable to the datagridview.
Upvotes: 2