views:

36

answers:

2

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.

+2  A: 

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.

Carra
ooh,yeees.you 're right.:-D
mahnaz
+1  A: 

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");
Stuart Dunkeld
@Stuart Dunkeld:If I want to add "x" in row[3] and column[4],where I can isert number of row and column?
mahnaz
@mahnaz Once you've added the rows you can address them by index.
Stuart Dunkeld