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

本文关键字:列表 问题 中网 网格 | 更新日期: 2023-09-27 18:09:47

我试图渲染一个简单的List到一个网格,如

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

我没有得到任何错误,但无法在网格中显示列表。下面是完整的代码

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;
        }
    }
}

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

DataGridView不能绑定到原始值列表(如int, decimal, DateTime, enum, string等),因为它需要包含具有属性的对象列表

最简单的方法是使用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();
}
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;
    }
}

我不认为你可以绑定一个enum到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;