[ADO.NET] 使用 BindingSource 與 bindingNavigator

[ADO.NET] 使用 BindingSource 與 bindingNavigator

BindingSource 元件 BindingSource 類別都可以讓資料繫結於控制項,欲知詳情可在回到MSDN查閱

1.首先我先隨便建立一個DataTable,然後把 DataTable塞到 BindingSource 類別的DataSource屬性裡

private void Form1_Load(object sender, EventArgs e)
{
    DataTable table = new DataTable("newTable");
    if (!File.Exists(this._file))
    {
        string[] field = new string[] { "ID", "Name", "Phone" };
        foreach (string item in field)
        {
            DataColumn column = new DataColumn();
            column.Caption = item;
            column.ColumnName = item;
            column.AllowDBNull = false;
            table.Columns.Add(column);
        }
        DataRow row = table.NewRow();
        row["ID"] = "1";
        row["Name"] = "余小章";
        row["Phone"] = "1234";
        table.Rows.Add(row);
        row = table.NewRow();
        row["ID"] = "2";
        row["Name"] = "王小明";
        row["Phone"] = "1234678";
        table.Rows.Add(row);
        table.WriteXml(this._file);
    }
    else
    {
        table.ReadXmlSchema(this._file);
        table.ReadXml(this._file);
    }
    this._Bind.DataSource = table;
}

2.然後加入dataGridView1與bindingNavigator1控制項

image

再加入幾個textBox控制項,如下圖

image

3.建立項資料繫結 ,參考http://www.dotblogs.com.tw/yc421206/archive/2009/10/30/11360.aspx

this.dataGridView1.DataSource=_Bind;
this.bindingNavigator1.BindingSource = this._Bind;
txtID.DataBindings.Add("Text", this._Bind, "ID", true);
txtName.DataBindings.Add("Text", this._Bind, "Name", true);
txtPhone.DataBindings.Add("Text", this._Bind, "Phone", true);

4.存檔

private void bindingNavigatorSave_Click(object sender, EventArgs e)
{
    if (this._Bind == null)
        return;
    this._Bind.MoveNext();
    DataTable table = this._Bind.DataSource as DataTable;
    table.WriteXml(this._file);
}

5.讀檔

{ 
    if (File.Exists(this._file))
        return;
    DataTable table = new DataTable("newTable");
    table.ReadXmlSchema(this._file);
    table.ReadXml(this._file);
}

 

完成之後所有的控制項都被繫結到同一個DataTable裡面

範例下載

CS_BindingSource.zip

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo