【问题标题】:Bind Datagridview to StringCollection将 Datagridview 绑定到 StringCollection
【发布时间】:2012-04-13 12:06:22
【问题描述】:

是否可以将 Datagridview 绑定到 StringCollection ? 我试图以某种方式做到这一点

    StringCollection dict = Settings.Default.MyDict;
    BindingSource bs = new BindingSource();
    bs.DataSource = dict;
    this.DGV.DataSource = bs;

芽而不是集合datagridview的项目显示项目的长度。

【问题讨论】:

标签: c# winforms datagridview .net-2.0


【解决方案1】:

问题在于,当它绑定到StringCollection 时,基础类型是string,因此它会从类型string 中提取它找到的第一个属性来显示。该属性是长度。

您可以做的是将您的StringCollection 包装在您自己制作的类中,并公开一个将显示string 文本的属性。

string 的包装类:

public class MyString
{
    private string _myString;

    public string Text
    {
        get { return _myString; }
        set { _myString = value; }
    }

    public MyString(string str)
    {
        _myString = str;
    }
}

你的代码变成:

StringCollection dict = Settings.Default.MyDict; 
// put your string in the wrapper
List<MyString> anotherdict = new List<MyString>();
foreach (string str in dict)
{
    anotherdict.Add(new MyString(str));
}
BindingSource bs = new BindingSource();
// bind to the new wrapper class
bs.DataSource = anotherdict;
this.DGV.DataSource = bs; 

【讨论】:

  • 是否可以通过更改 DataMember 属性在没有包装器的情况下做到这一点?
  • @Ask,DataMember 采用属性的名称。如果您查看String's Public Properties,您会发现它只有两个属性,并且没有一个可以让您获得字符串的文本。因此,您无法将DataMember 设置为可以获取文本的任何内容。解决它的唯一方法是提供您自己的类,该类提供自己的属性来公开字符串。你能用List&lt;&gt;、BindingList&lt;&gt;、ObservableCollection等代替StringCollection吗?
  • 感谢您的评论。默认情况下,您只能在属性编辑器中选择 StringCollection,这就是我坚持使用它的原因。
猜你喜欢
  • 2010-10-19
  • 1970-01-01
  • 2011-05-16
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多