Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add DataTable Row to DataGridView without binding

I have a predefined DataGridView that I need to add rows to from a DataTable without data binding. I am trying to use the DataGridView.Rows.Add() method programmatically however, I do not know the column names of the DataTable. The columns in the DataTable are in the same order as the DataGridView but how do I add them to the DataGridView without knowing the column names?

like image 646
user10001110101 Avatar asked Apr 27 '26 06:04

user10001110101


1 Answers

Say your DataGridView exists but has no columns. You can do this:

foreach (DataColumn dc in yourDataTable.Columns) {

     yourDataGridView.Columns.Add(new DataGridViewTextBoxColumn());

}

Then add the row data:

foreach(DataRow dr in yourDataTable.Rows) {

     yourDataGridView.Rows.Add(dr.ItemArray);

}

Now, if the default textbox column isn't sufficient, you might have to create a column with a different cell template.

like image 64
JMS Avatar answered Apr 28 '26 19:04

JMS