DataGridView 数据绑定的一般过程

原文地址为: DataGridView 数据绑定的一般过程

      但在多数情况下,都将绑定到一个 BindingSource 组件,由该组件来管理与数据源交互的详细信息。 BindingSource 组件可表示任何 Windows 窗体数据源,并在选择或修改数据位置时提供很大的灵活性。

    1、实现一个用于处理数据库数据检索的详细信息的方法。下面的代码示例实现一个 GetData 方法,该方法对一个 SqlDataAdapter 组件进行初始化,并使用该组件填充 DataTable。然后,将 DataTable 绑定到 BindingSource 组件。请确保将 connectionString 变量的值设置为与数据库相应的值。

None.gif private   void  GetData( string  selectCommand)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
try
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        String connectionString 
=
InBlock.gif            
"Integrated Security=SSPI;Persist Security Info=False;" +
InBlock.gif            
"Initial Catalog=Northwind;Data Source=localhost";
InBlock.gif        dataAdapter 
= new SqlDataAdapter(selectCommand, connectionString);
InBlock.gif
InBlock.gif        SqlCommandBuilder commandBuilder 
= new SqlCommandBuilder(dataAdapter);
InBlock.gif
InBlock.gif        DataTable table 
= new DataTable();
InBlock.gif        table.Locale 
= System.Globalization.CultureInfo.InvariantCulture;
InBlock.gif        dataAdapter.Fill(table);
InBlock.gif        bindingSource1.DataSource 
= table;
InBlock.gif
InBlock.gif        dataGridView1.AutoResizeColumns( 
InBlock.gif            DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
catch (SqlException)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        MessageBox.Show(
"To run this example, replace the value of the " +
InBlock.gif            
"connectionString variable with a connection string that is " +
InBlock.gif            
"valid for your system.");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

    2、在窗体的 Load 事件处理程序中,将 DataGridView 控件绑定到 BindingSource 组件,并调用 GetData 方法从数据库中检索数据

None.gif private   void  Form1_Load( object  sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    dataGridView1.DataSource 
= bindingSource1;
InBlock.gif    GetData(
"select * from Customers");
ExpandedBlockEnd.gif}

转MSDN
转载请注明本文地址: DataGridView 数据绑定的一般过程

猜你喜欢

转载自blog.csdn.net/dearbaba_8520/article/details/81257969
今日推荐