C# 如何将列表绑定到 dataGridView?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1228539/
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
How to bind list to dataGridView?
提问by Amc_rtty
I seem to be running around in circles and have been doing so in the last hours.
我似乎在绕圈子跑,并且在过去的几个小时里一直在这样做。
I want to populate a datagridview from an array of strings. I've read its not possible directly, and that I need to create a custom type that holds the string as a public property. So I made a class:
我想从字符串数组中填充 datagridview。我已经阅读了它不可能直接,并且我需要创建一个自定义类型,将字符串保存为公共属性。所以我做了一个类:
public class FileName
{
private string _value;
public FileName(string pValue)
{
_value = pValue;
}
public string Value
{
get
{
return _value;
}
set { _value = value; }
}
}
this is the container class, and it simply has a property with the value of the string. All I want now is that string to appear in the datagridview, when I bind its datasource to a List.
这是容器类,它只有一个带有字符串值的属性。我现在想要的是该字符串出现在 datagridview 中,当我将其数据源绑定到列表时。
Also I have this method, BindGrid() which I want to fill the datagridview with. Here it is:
我也有这个方法 BindGrid(),我想用它来填充 datagridview。这里是:
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
colFileName.CellTemplate = cell; colFileName.Name = "Value";
colFileName.HeaderText = "File Name";
colFileName.ValueType = typeof(FileName);
//add the column to the datagridview
gvFilesOnServer.Columns.Add(colFileName);
//fill the string array
string[] filelist = GetFileListOnWebServer();
//try making a List<FileName> from that array
List<FileName> filenamesList = new List<FileName>(filelist.Length);
for (int i = 0; i < filelist.Length; i++)
{
filenamesList.Add(new FileName(filelist[i].ToString()));
}
//try making a bindingsource
BindingSource bs = new BindingSource();
bs.DataSource = typeof(FileName);
foreach (FileName fn in filenamesList)
{
bs.Add(fn);
}
gvFilesOnServer.DataSource = bs;
}
Finally, the problem: the string array fills ok, the list is created ok, but I get an empty column in the datagridview. I also tried datasource= list<> directly, instead of = bindingsource, still nothing.
最后,问题:字符串数组填充正常,列表创建正常,但我在datagridview中得到一个空列。我也直接试过datasource=list<>,而不是=bindingsource,还是什么都没有。
I would really appreciate an advice, this has been driving me crazy.
我真的很感激一个建议,这让我发疯了。
采纳答案by sloth
Use a BindingListand set the DataPropertyName-Property of the column.
使用BindingList并设置列的DataPropertyName-Property。
Try the following:
请尝试以下操作:
...
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value",
HeaderText = "File Name",
DataPropertyName = "Value" // Tell the column which property of FileName it should use
};
gvFilesOnServer.Columns.Add(colFileName);
var filelist = GetFileListOnWebServer().ToList();
var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList
//Bind BindingList directly to the DataGrid, no need of BindingSource
gvFilesOnServer.DataSource = filenamesList
}
回答by PsCraft
Instead of create the new Container class you can use a dataTable.
您可以使用 dataTable 代替创建新的 Container 类。
DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");
dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });
myDataGridView.DataSource = dt;
More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString
您可以在此处找到有关此问题的更多信息:http: //psworld.pl/Programming/BindingListOfString
回答by Nasir Mahmood
may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you
可能有点晚,但对未来有用。如果您不需要设置单元格的自定义属性并且只关心标题文本和单元格值,那么此代码将帮助您
public class FileName
{
[DisplayName("File Name")]
public string FileName {get;set;}
[DisplayName("Value")]
public string Value {get;set;}
}
and then you can bind List as datasource as
然后您可以将 List 绑定为数据源
private void BindGrid()
{
var filelist = GetFileListOnWebServer().ToList();
gvFilesOnServer.DataSource = filelist.ToArray();
}
for further information you can visit this page Bind List of Class objects as Datasource to DataGridView
有关更多信息,您可以访问此页面将类对象列表作为数据源绑定到 DataGridView
hope this will help you.
希望这会帮助你。
回答by user3214451
Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:
如 user927524 所述,使用 DataTable 是有效的。您也可以通过手动添加行来实现,这不需要添加特定的包装类:
List<string> filenamesList = ...;
foreach(string filename in filenamesList)
gvFilesOnServer.Rows.Add(new object[]{filename});
In any case, thanks user927524 for clearing this weird behavior!!
无论如何,感谢 user927524 清除这种奇怪的行为!!
回答by Kevin Finck
I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.
我知道这很旧,但这让我挂了一段时间。列表中对象的属性必须是实际的“属性”,而不仅仅是公共成员。
public class FileName
{
public string ThisFieldWorks {get;set;}
public string ThisFieldDoesNot;
}