C# Window Form DataGridView 数据绑定的一般过程
时间:2010-06-24 来源:kuncomputer
但在多数情况下,都将绑定到一个 BindingSource 组件,由该组件来管理与数据源交互的详细信息。BindingSource 组件可表示任何 Windows 窗体数据源,并在选择或修改数据位置时提供很大的灵活性。
1、实现一个用于处理数据库数据检索的详细信息的方法。下面的代码示例实现一个 GetData 方法,该方法对一个 SqlDataAdapter 组件进行初始化,并使用该组件填充 DataTable。然后,将 DataTable 绑定到 BindingSource 组件。请确保将 connectionString 变量的值设置为与数据库相应的值。
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);
{
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);
//Oracle DataSet 操作
/*
OracleConnection Conn = new OracleConnection(connectionString); string OraCmd = "select time,ywid,cphm,hpzl,lczt1,jbr from bfc_qqdlinfo order by time desc"; OracleDataAdapter dataAdapter = new OracleDataAdapter(OraCmd, Conn); this.ds = new DataSet(); dataAdapter.Fill(ds);
*/
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 方法从数据库中检索数据
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");
}
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Customers");
}
相关阅读 更多 +