简体   繁体   English

是否有必要将“列表”绑定到数据网格视图?

[英]is it necessary to bind a 'List' to a datagridview?

I have a DataGridView in which i need to show just one row.我有一个 DataGridView,我只需要在其中显示一行。 The values inside grid are editable.网格内的值是可编辑的。 What i need to know is whether i can bind an object to the grid or need to add the object to a list and bind that list instead.我需要知道的是我是否可以将对象绑定到网格或需要将对象添加到列表并绑定该列表。 I am currently doing something like this:我目前正在做这样的事情:

class myclass
{
int id;
string name;
}
// some code here
myclass myObject = new myclass();
//initialized data in myObject
list<myclass> objectList = new list<myclass>();
objectList.Add(myObject);
// again some code
DataGridView myGrid = new DataGridView();
//added necessary columns
myGrid.DataSource = objectList;

DataTable is usually the way to go to put custom data in a DataGridView . DataTable通常是将自定义数据放入DataGridView Here's a minimal example:这是一个最小的例子:

DataTable table = new DataTable("Info");
table.Columns.Add(new DataColumn("index", typeof(Int32)));
table.Columns.Add(new DataColumn("data", typeof(String)));
for (Int32 i = 0; i < myList.Length; i++)
{
    DataRow row = symbolsTable.NewRow();
    row[0] = i;
    row[1] = myList[i];
    table.Rows.Add(row);
}
this.myDgrv.DataSource = table;

Of course, this will not actually be linked to the original List;当然,这实际上不会链接到原始列表; you'll have to handle that yourself.你必须自己处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM