2014-02-24 145 views
0

我正在寻找一种向datagrid添加新行的简单方法。所以,我有:向DataGridView添加新行C#

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++;} 

我的错误在哪里?我在这里读过一些文章,但没有答案。

+0

你是否收到我认为的索引错误? – LarsTech

+0

@LarsTech是的!是! – Maria

+0

什么是tInArr? –

回答

2

,如果你没有数据源,那么你可以去以下方式:

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"; 
在你的代码

它应该是:

// 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 
} 
+0

我是这么说的!有用!谢谢! – Maria

+0

不客气:) – Koryu

0

首先您可以创建数据表,然后您可以将datagrid的数据源设置为很长但易于维护。

这样

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; 
1

在这里你可以使用datable然后像这样迭代你的循环:

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(); 
    }