项目结构
一、绑定数据方式
通过DataTable绑定
DataTable table =new DataTable();dgv.DataSource = table;
通过ArrayList绑定
class Book{ public string ID { get; set; } public string No { get; set; } public string Name { get; set; }}private void InitByDataTable(){ Listlist = new List (); for (int i = 0; i < 10; i++) { list.Add(new Book() {ID = i.ToString(),No = i.ToString(), Name = "Book"+i }); } dgv.DataSource = list; //设置可见性 dgv.Columns[0].Visible = false; //设置列标题 dgv.Columns[1].HeaderText = "编码"; dgv.Columns[2].HeaderText = "名称"; //设置类宽 dgv.Columns[2].Width = 100;}
通过Dictionary绑定
private void InitByDictionary(){ Dictionarydictionary = new Dictionary (); for (int i = 0; i < 10; i++) { dictionary.Add(i.ToString(), "Book" + i); } dgv.DataSource = (from v in dictionary select new { ID = v.Key, Key = v.Key, Value = v.Value }).ToArray();}