将Datagridview绑定到StringCollection

时间:2012-04-13 12:06:22

标签: c# winforms datagridview .net-2.0

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

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

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

1 个答案:

答案 0 :(得分:2)

问题在于,当它绑定到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;