C#中网格中渲染列表的问题

时间:2016-09-30 17:37:22

标签: c# winforms

我正在尝试将简单的List呈现为像

这样的网格
var sr = new BindingSource();
sr.DataSource = str;
dataGridView1.DataSource = sr;

我没有收到任何错误但无法在Grid中显示列表。这是整个代码

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Enum
{
    public enum Sex {Male, Female, Other };
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<Sex> str = new List<Sex>();
            str.Add(Sex.Female);
            str.Add(Sex.Male);

            var sr = new BindingSource();
            sr.DataSource = str;
            dataGridView1.DataSource = sr;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public class Person
    {
        public string Name { get; set; }
        public string Lastname { get; set; }
        public Sex Sex { get; set; }
    }

    public enum Sex { Male, Female, Other };

    private void button1_Click(object sender, EventArgs e)
    {
        BindingList<Person> persons = new BindingList<Person>();

        persons.Add(new Person() { Name = "Joe", Lastname = "Doe" , Sex = Sex.Male});
        persons.Add(new Person() { Name = "Nancy", Lastname = "Foo" , Sex = Sex.Female});

        dataGridView1.DataSource = persons;
    }
}

答案 1 :(得分:1)

我认为你不能将枚举绑定到GridView。这就是我可以工作的原因

public class Person
{
    public Sex Gender { get; set; }
}

您需要使用BindingList,因为列表未实现IBindingList

var list = new List<Person>()
{
    new Person { Gender = Sex.Male, },
    new Person { Gender = Sex.Female, },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
dataGridView1.DataSource = source;  

答案 2 :(得分:1)

DataGridView无法绑定到原始值列表(例如intdecimalDateTimeenumstring等。)因为它需要一个包含属性的对象的列表。

最简单的方法是将LINQ投影用于具有单一属性的匿名类型(完全不需要BindingSource):

private void button1_Click(object sender, EventArgs e)
{
    List<Sex> str = new List<Sex>();
    str.Add(Sex.Female);
    str.Add(Sex.Male);

    dataGridView1.DataSource = str.Select(value => new { Sex = value }).ToList();
}