WinForm DataGridView bind generic List (List <T>)/ArrayList does not show the reason and solution, arraylist generic
Background: I accidentally encountered a small problem and hoped to help some people!
I. Problems
WinForm DataGridView bind generic List (List <T>)/ArrayList not displayed, UI
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); maid = 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 ;}}}Ii. Solution
In fact, it is very simple, but many friends may not consider it, because it is not a problem of generic List or ArrayList,
Just change the code:
public class User { public int ID; public string UserName; public string NickName; public string Phone; public string QQ; }
Is:
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; } }
Okay.
Iii. Simple Explanation
The get and set fields are not defined, and the attribute is defined. For security reasons, the data source binding of the DataGridView can only be a public attribute, but cannot access fields. Many other controls share the same situation.