創建DataTable與DataGridView進行綁定


private DataTable dt = new DataTable();

BindingSource bs = new BindingSource();

 

/// <summary>
/// 初始化DataTable
/// </summary>
public void InitDataTable()

//不允許自動生成,若改為允許,界面會自動增加DataTable列,那么界面上既會包含DataGridView中定義的列,也會包含DataTable定義的列
this.dataGridView1.AutoGenerateColumns = false;

DataColumn col = new DataColumn("No", typeof(int));
dt.Columns.Add(col);
dt.Columns.Add(new DataColumn("Addr", typeof(string)));
dt.Columns.Add(new DataColumn("FuntionType", typeof(string)));
dt.Columns.Add(new DataColumn("Result", typeof(string)));

bs.DataSource = dt;
this.dataGridView1.DataSource = bs;

 

//將DataGridView中的列與DataTable中的列進行數據綁定,this.cloNum為列名

this.colNum.DataPropertyName = "No";
this.colAddress.DataPropertyName = "Addr";
this.colFunction.DataPropertyName = "FuntionType";
this.colResult.DataPropertyName = "Result";
}

 

2.也可以只創建一個DataGridView,而不創建任何的列,直接用BingdingSource綁定的DataTable來綁定DataGridView的數據源,那么DataTable中的所有數據便會顯示在界面上,有一個缺點,就是界面上顯示的列名稱是DataTable中的名稱,而不能自定義了。好處是不需要再操作復雜的DataGridView來對頁面進行數據的增刪改,而只要操作DataTable即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM