1

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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");

2 Comments

If I want to add "x" in row[3] and column[4],where I can isert number of row and column?
@mahnaz Once you've added the rows you can address them by index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.