背景:無意間遇到了一個不大不小的問題,希望對一些遇到的人有所幫助!
WinForm DataGridView 綁定泛型List (List
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public delegate T BorrowReader<out T>(IDataReader reader); public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private List<User> GetUsers(IDataReader reader) { var list = new List<User>(); while (reader.Read()) { list.Add(new User() { ID = reader.GetInt32(reader.GetOrdinal("ID")), UserName = reader.GetString(reader.GetOrdinal("UserName")), NickName = reader.GetString(reader.GetOrdinal("NickName")), Phone = reader.GetString(reader.GetOrdinal("Phone")), QQ = reader.GetString(reader.GetOrdinal("QQ")), }); } return list; } private void btnTest_Click(object sender, EventArgs e) { dataGridView1.AutoGenerateColumns = false; var list = MyDb.LendReader("select * from Users where 0=0", GetUsers); dataGridView1.DataSource = list; } } public class User { public int ID; public string UserName; public string NickName; public string Phone; public string QQ; } public class MyDb { public static T LendReader<T>(string sql, BorrowReader<T> borrowReader) { using (OleDbConnection connection = CreateConnection()) { connection.Open(); OleDbCommand c = new OleDbCommand(sql, connection); OleDbDataReader r = c.ExecuteReader(); return borrowReader(r); } } private static OleDbConnection CreateConnection() { string dbName = Path.Combine(Application.StartupPath, "MyData.mdb"); OleDbConnection c = new OleDbConnection { ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName }; return c; } } }
其實很簡單,只是很多朋友可能沒有考慮到,因為這壓根不是什麼泛型List或者ArrayList的問題,
只要改代碼:
public class User { public int ID; public string UserName; public string NickName; public string Phone; public string QQ; }
為:
public class User { public int ID{ get; set; } public string UserName { get; set; } public string NickName { get; set; } public string Phone { get; set; } public string QQ { get; set; } }
就好了
沒定義get、set的是字段,定義了就是屬性了,為了安全性考慮,DataGridView 的數據源綁定只能是被公開了的屬性,而無權訪問字段。很多其他控件也有同樣的情況。