user1420914
user1420914

Reputation: 279

Add rows to datagridview dynamically

I usually don't post questions, and I know this answer is already out there somewhere but I'm not finding it for some reason. Basically, I have a datagridview that has a variable number of columns, and variable number of rows. So when I'm building it for the screen, I first add the columns using this code:

// Set column names
for (int i = 0; i < count; i++)
{
  fieldName = fromFileFields[i];
  dtaRecordDisplay.Columns.Add(fromFileFields[i}, fromFileFields[i});
}

Now, I would like to populate the rows in the view with something like this:

// Set row data
for (int i = 0; i < count; i++)
{
  dtaRecordDisplay.Rows.Add(Row1, Row2, etc., etc., etc..........);
}

I'm having a hard time figuring out the loop to be able to add all rows of data at once. Does anyone have any ideas on how to accomplish that?

Thanks in advance!

Upvotes: 2

Views: 21094

Answers (3)

Sarath KGW
Sarath KGW

Reputation: 21

Try following code, you can add rows to dataGridViews without out any data Sources or data table.

dataGridView1.AllowUserToAddRows = true;
dtaGridView1 row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "Your cell 0 Data";
row.Cells[1].Value = "Your cell 1 Data";
row.Cells[2].Value = "Your cell 2 Data";
   ………….
row.Cells[n].Value = "Your cell n Data";
dataGridView1.Rows.Add(row);

Upvotes: 0

wert1990
wert1990

Reputation: 51

You need to make a DataTable, and bind that to your grid view. Then add the rows and colums to that, like Marc says:

https://stackoverflow.com/a/35604744/5882760

The reason for that is, that the columns of the grid view instance only contain information on how to display the data from the attached DataTable.

They contain the information about what columbs to display, in what order, etc.

Upvotes: 0

Marc
Marc

Reputation: 3959

In this case I would fill a DataTable with columns and rows to work with, and bind that to the grid.

DataTable dt = new DataTable();

// first add your columns
for (int i = 0; i < count; i++)
{
    dt.Columns.Add(fromFileFields[i]);
}

// and then add your rows
for (int i = 0; i < count; i++)
{
    var row = dt.NewRow();
    // Set values for columns with row[i] = xy
    dt.Rows.Add(row);
}

datagridview.DataSource = dt;

Upvotes: 8

Related Questions