将Datagridview绑定到StringCollection [英] Bind Datagridview to StringCollection

查看:109
本文介绍了将Datagridview绑定到StringCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to bind Datagridview to StringCollection ? I tried to do it in a manner

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

Bud代替集合data的项目gridview显示项目的长度。

Bud instead of items of the collection datagridview shows lengths of the items.

推荐答案

问题是,当它绑定到 StringCollection 时,基础类型为 string ,以便从显示的 string 类型中拉出第一个属性。该属性是长度。

The problem is that when it binds to StringCollection, the underlying type is string so it pulls out the first property that it finds from type string to display. That property is Length.

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

What you can do is wrap your StringCollection in a class of your own making and expose a property that will display the string's text.

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; 

这篇关于将Datagridview绑定到StringCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆