但在多數情況下,都將綁定到一個 BindingSource 組件,由該組件來管理與數據源交互的詳細信息。
BindingSource 組件可表示任何 Windows 窗體數據源,並在選擇或修改數據位置時提供很大的靈活性。
1、實現一個用於處理數據庫數據檢索的詳細信息的方法。下面的代碼示例實現一個
GetData 方法,該方法對一個 SqlDataAdapter 組件進行初始化,並使用該組件填充 DataTable。然後,將
DataTable 綁定到
BindingSource 組件。請確保將
connectionString 變量的值設置為與數據庫相應的值。

private void GetData(string selectCommand)



{

try


{

String connectionString =

"Integrated Security=SSPI;Persist Security Info=False;" +

"Initial Catalog=Northwind;Data Source=localhost";

dataAdapter = new SqlDataAdapter(selectCommand, connectionString);


SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);


DataTable table = new DataTable();

table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);

bindingSource1.DataSource = table;


dataGridView1.AutoResizeColumns(

DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

}

catch (SqlException)


{

MessageBox.Show("To run this example, replace the value of the " +

"connectionString variable with a connection string that is " +

"valid for your system.");

}

}
2、在窗體的 Load 事件處理程序中,將
DataGridView 控件綁定到
BindingSource 組件,並調用
GetData 方法從數據庫中檢索數據

private void Form1_Load(object sender, System.EventArgs e)



{

dataGridView1.DataSource = bindingSource1;

GetData("select * from Customers");

}
轉自 MSDN