zoukankan      html  css  js  c++  java
  • DataGridView 数据绑定的一般过程

    DataGridView 数据绑定的一般过程

          但在多数情况下,都将绑定到一个 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

    ——————————————————————————————————————
    男人的自信来自一个女人对他的崇拜,

    女人的高傲来自一个男人对她的倾慕。

  • 相关阅读:
    代码希望HTML5初探CSS3新特性小示例
    myeclipse及eclipse的优化
    window7如何提高到最高权限
    大麦茶
    poj3292
    poj3278
    poj3100
    poj3117
    poj3299
    Presto性能调优的五大技巧
  • 原文地址:https://www.cnblogs.com/qqhfeng/p/2403261.html
Copyright © 2011-2022 走看看