zoukankan      html  css  js  c++  java
  • 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");
    }
  • 相关阅读:
    wireshark如何抓取本机包
    模拟post请求方法
    Spring Boot中使用RabbitMQ
    Dubbo注册中心的四种配置方式详解
    spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情
    zookeeper 大量连接断开重连原因排查
    分布式一致性协议之:Gossip(八卦)算法
    MongoDB分析工具之一:explain()语句分析工具
    MongoDB分析工具之二:MongoDB分析器Profile
    MySQL安装
  • 原文地址:https://www.cnblogs.com/ArRan/p/2749682.html
Copyright © 2011-2022 走看看