C# DataGridView:使用数组或 List<t> 添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14281473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridView: Add new row using an array or List<t>
提问by Kesandal
I've two listbox-elements in my form. The items in listbox1 are representing the columns in my DataGridView, the items in my listbox2 are representing the rows in my DataGridView.
我的表单中有两个列表框元素。listbox1 中的项目代表我的 DataGridView 中的列,我的 listbox2 中的项目代表我的 DataGridView 中的行。
foreach (var el in listBox1Elements)
{
// code...
dataGridView1.Columns.Add(col);
}
Since items in listbox1 can be added or deleted I've a problem with my current solution.
由于可以添加或删除 listbox1 中的项目,因此我当前的解决方案存在问题。
dataGridView1.Rows.Add("test","some","data","even","more","data");
I wonder if there is a solution for using a List. Then my code could look something like this:
我想知道是否有使用列表的解决方案。然后我的代码看起来像这样:
foreach (var el in listBox2Elements)
{
myList.add("some text");
}
dataGridView1.Rows.Add(myList);
采纳答案by spajce
Something like
就像是
foreach (var el in listBox2Elements)
myList.add("some text");
foreach (var item in myList)
dataGridView1.Rows.Add(item.., item.., item..);
or
或者
dataGridView1.DataSource = myList.ToList()
回答by Vogel612
well thats some hard task to do without a store object. there you could easily go:
好吧,如果没有商店对象,那就是一些艰巨的任务。你可以很容易地去那里:
//Not taking guarantee for this approach
Store.DataSource.add(new object[]{"some text"});
Store.DataBind();
or you define a new Data source object and fill it with the list items (via loop) and do that again after doing:
或者您定义一个新的数据源对象并用列表项填充它(通过循环),然后在执行以下操作后再次执行:
(list<string>) data_list.add("some text");
//repopulate data object and set a Store.DataSource;
Store.dataBind();
and for deleting objects you would delete them from the list<string>
item and update the store like above
对于删除对象,您将从项目中删除它们list<string>
并像上面一样更新商店
//population for the data object:
for(int x=0; x<= data_list.length(); x++)
{
data.add(new object[]{data_list[x]});
}
回答by Michael Murphy
How about:
怎么样:
foreach (var el in listBox2Elements)
{
myList.add("some text");
}
dataGridView1.Rows.Add(myList.ToArray());