Sneha
Sneha

Reputation: 1

DataGridView in C#

I am using a DataGridView to display some data in my application.
The data in the table gets changed dynamically according to the users input.
I am able to retrieve the data according to the user.

I have to add an extra column named ID and fill in the values serially starting from 1 to the number of rows which are generated dynamically.

I had added the column using dgrid.columns.add("UID");

But how to insert values at runtime?

Upvotes: 0

Views: 282

Answers (1)

Oscar Mederos
Oscar Mederos

Reputation: 29863

Seeing your code, it is not correct to do:

dgrid.Columns.Add("UID");

You will have to do:

dgrid.Columns.Add("uidColumn", "UID");

To modify/add the value of an existing cell, if the row already exists, you can do:

dgrid.Rows[0].Cells["uidColumn"].Value = myValue;

That will modify the value of the column with name uidColumn and row 0. According to your problem, all you have to do is:

for (int i = 0; i < dgrid.Rows.Count; i++) {
    dgrid.Rows[i].Cells["uidColumn"].Value = GetValueOfRow(i);
}

supposing that you have a method GetValueOfRow that receives a row index and returns the value you need in the ID column in that row.

Upvotes: 2

Related Questions