Background: Inadvertently encountered a problem of a moderate, I hope to some people met with help!
First, the question
WinForm DataGridView binding Generic List (List <T>)/arraylist not displayed, UI
The code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Data.OleDb;usingSystem.IO;usingSystem.Windows.Forms;namespacewindowsformsapplication1{Public DelegateTBorrowreader< outt> (IDataReaderreader); Public Partial classFormMain: Form{ PublicFormMain () {InitializeComponent (); } PrivateList<User> Getusers (IDataReaderreader) { varlist =NewList<User> (); while(reader. Read ()) {list. ADD (NewUser() {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")), }); } returnlist; } private voidbtnTest_Click (Objectsender,EventArgse) {datagridview1.autogeneratecolumns =false; varlist =MyDb. Lendreader ("SELECT * from Users where 0=0", getusers); Datagridview1.datasource = list; } } Public classUser{ public intID; Public StringUserName; Public Stringnickname; Public StringPhone; Public StringQQ; } Public classMyDb{ Public StaticT lendreader<t> (stringSQL,Borrowreader<T> Borrowreader) { using(OleDbConnectionconnection = CreateConnection ()) {connection. Open (); OleDbCommandC =NewOleDbCommand(sql, connection); OleDbDataReaderr = C.executereader (); returnBorrowreader (R); } } private staticOleDbConnectioncreateconnection () {stringDbName =Path. Combine (Application. StartupPath,"Mydata.mdb"); OleDbConnectionC =NewOleDbConnection{ConnectionString ="Provider=Microsoft.Jet.OLEDB.4.0;Data source="+ dbName}; returnC; } }}
Second, the solution
Actually very simple, just a lot of friends may not consider, because this is not a generic list or ArrayList problem,
Just change the code:
User { ID; UserName; nickname; Phone; QQ; }
For:
Public classUser{ public intid{Get; Set; } Public StringUserName {Get; Set; } Public StringNickname {Get; Set; } Public StringPhone {Get; Set; } Public StringQQ {Get; Set; } }
Just fine.
Three, simple explanation
There is no definition of GET, set is a field, defined is a property, for security reasons, the DataGridView data source binding can only be exposed properties, and do not have access to the field. Many other controls also have the same situation.
WinForm DataGridView binding Generic List (list<t>)/arraylist does not show cause and resolution