1. 程式人生 > >創建DataTable與DataGridView進行綁定

創建DataTable與DataGridView進行綁定

oid table datagrid ner res aso view ini 自動增加

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";
}

創建DataTable與DataGridView進行綁定