• 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");
    }
  • 相关阅读:
    机器视觉资料整理
    《用TCP/IP进行网络互连》读书笔记
    Win Form不能响应键盘事件
    C语言 字符串前加L的意义 如:L“A”
    UniCode 下 CString 转 char* 的方法(转)
    BATCH
    HALCON不支持的设备中,获取图像
    关于FragmentManager动态管理Fragment时Fragment生命周期的探究
    关于如何惟一地标识一台Android设备的综合性讨论
    如何使ActionBar不那么单调
  • 原文地址:https://www.cnblogs.com/ArRan/p/2749682.html
Copyright © 2020-2023  润新知