1

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

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

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

4

1 回答 1

2

问题在于,当它绑定到 时StringCollection,底层类型是string这样的,它会从类型中提取出它找到的第一个属性string来显示。该属性是长度。

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

包装类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; 
于 2012-04-13T15:10:01.217 回答