Reputation: 77
I searching for a easy method for adding new row to datagrid. So, what I have:
dataGridView2.ColumnCount = 4;
int w = 0;
foreach (var item in tInArr)
{...
dataGridView2.Rows.Add();
dataGridView2[0, w].Value = muTat3.ToString();
dataGridView2[1, w].Value = item.ToString();
....
w++;}
Where is my mistake? I've read some articles here, but there's no answers.
Upvotes: 0
Views: 1699
Reputation: 1381
if you have no datasource, then you can go the following way:
int rowIndex = dataGridView1.Rows.Add();
dataGridView1[0, rowIndex].Value = "value1"; // 0 for first column
dataGridView1[1, rowIndex].Value = "value2"; // 1 for second column
rowIndex = dataGridView1.Rows.Add();
dataGridView1[0, rowIndex].Value = "value3";
dataGridView1[1, rowIndex].Value = "value4";
in your code it should be:
// dataGridView2.ColumnCount = 4;
int w = 0;
foreach (var item in tInArr)
{...
w = dataGridView2.Rows.Add();
dataGridView2[0, w].Value = muTat3.ToString();
dataGridView2[1, w].Value = item.ToString();
....
//w++; this is not required
}
Upvotes: 2
Reputation: 1389
Here you can use datable then iterate your loop like this way :
foreach (DataRow rows in dt.Rows)
{..
int w = dataGridView2.Rows.Add();
dataGridView2[0, w].Value = rows[0].ToString();
dataGridView2[1, w].Value = rows[1].ToString();
}
Upvotes: 1
Reputation: 744
First You create the datatable and then you can set the datasource of datagrid its long but easy to maintain.
like this
DataTable table = new DataTable();
table.Columns.Add("Check", typeof(bool));
table.Columns.Add("Path", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(false, "", DateTime.Now);
dataGridView2.DataSource = table;
Upvotes: 0