.NET / C# 将 IList<string> 绑定到 DataGridView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1104341/
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
.NET / C# Binding IList<string> to a DataGridView
提问by BuddyJoe
I have an IList<string>
returning from a function (as variable lst) and I set and then I
我有IList<string>
一个函数的返回值(作为变量 lst),我设置然后我
this.dataGridView1.DataSource = lst;
The datagrid adds one column labelled Length and then lists the length of each string. How do I make it just list the strings?
数据网格添加一列标有长度的列,然后列出每个字符串的长度。我如何让它只列出字符串?
回答by Marc Gravell
You really need a list of objects that havea string property. With .NET 3.5 you could cheat:
您确实需要一个具有字符串属性的对象列表。使用 .NET 3.5 你可以作弊:
.DataSource = list.Select(x=>new {Value = x}).ToList();
Otherwise create a dummy class and copy the data in manually...
否则创建一个虚拟类并手动复制数据...
回答by Ben
This is because DataGridViews show properties of the object. In this case the List only has one property "Length", therefore it can only display "Lenght" (regardless of DataType). You need to create a wrapper class to achieve what you want (a "MyString" class with a property of "Text", then have a List displayed in your grid).
这是因为 DataGridViews 显示对象的属性。在这种情况下,列表只有一个属性“长度”,因此它只能显示“长度”(与数据类型无关)。你需要创建一个包装类来实现你想要的(一个带有“Text”属性的“MyString”类,然后在你的网格中显示一个列表)。
Hope this helps
希望这可以帮助
Adding Code Example
添加代码示例
class MyString
{
private string _text;
public string Text
{ get
{
return _text;
}
set
{
_text = value;
}
}
}
'In the executing form
'在执行形式中
private List<MyString> foo()
{
List<MyString> lst = new List<MyString>();
MyString one = new MyString();
MyString two = new MyString();
one.Text = "Hello";
two.Text = "Goodbye";
lst.Add(one);
lst.Add(two);
return lst;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = foo();
}