DataGridView:使用数组或列表添加新行

本文关键字:添加 新行 列表 数组 DataGridView | 更新日期: 2023-09-27 17:51:17

我的表单中有两个listbox-element。listbox1中的项目代表我的DataGridView中的列,我的listbox2中的项代表我的DataGridView中的行。

foreach (var el in listBox1Elements)
{
// code...
dataGridView1.Columns.Add(col);
}

由于listbox1中的项目可以添加或删除,我对目前的解决方案有一个问题。

dataGridView1.Rows.Add("test","some","data","even","more","data");

我想知道是否有一个使用列表的解决方案。然后我的代码看起来像这样:

foreach (var el in listBox2Elements)
{
   myList.add("some text");
}
dataGridView1.Rows.Add(myList);

DataGridView:使用数组或列表<t>添加新行

类似

        foreach (var el in listBox2Elements)
            myList.add("some text");
        foreach (var item in myList)
            dataGridView1.Rows.Add(item.., item.., item..);

dataGridView1.DataSource = myList.ToList()

如何:

foreach (var el in listBox2Elements)
{
   myList.add("some text");
}
dataGridView1.Rows.Add(myList.ToArray());

如果没有存储对象,这是一项艰巨的任务。你可以很容易地看到:

//Not taking guarantee for this approach
Store.DataSource.add(new object[]{"some text"});
Store.DataBind();

或者定义一个新的数据源对象并用列表项填充它(通过循环),并在执行

之后再次执行该操作:
(list<string>) data_list.add("some text");
//repopulate data object and set a Store.DataSource;
Store.dataBind();

对于删除对象,您可以从list<string>项中删除它们并像上面那样更新存储

//population for the data object:
for(int x=0; x<= data_list.length(); x++)
{
 data.add(new object[]{data_list[x]});
}