【问题标题】:How to create a function that fills tow DataGridView in C#如何在 C# 中创建一个填充两个 DataGridView 的函数
【发布时间】:2019-04-16 21:29:53
【问题描述】:

我正在创建一个小型数据库应用程序,我必须在其中填充两个 DataGridView 使用流动函数命名为“DG1”和“DG2”:

private SQLiteDataAdapter DB;
    private DataSet DS = new DataSet();
    private DataTable DT = new DataTable();

    public void LoadData(DataGridView Grid, String fields, String table)
    {
        SetConnection();
        sql_con.Open();
        sql_cmd = sql_con.CreateCommand();
        string CommandText = "select " + fields + " from " + table;
        DB = new SQLiteDataAdapter(CommandText, sql_con);
        DS.Reset();
        DB.Fill(DS);
        DT = DS.Tables[0];
        Grid.DataSource = DT;
        sql_con.Close();
    }

在主窗体中调用后

LoadData(DG1, "*", "CLIENTS");

第一个网格会填满,但是当我调用第二种方法时

LoadData(DG2, "*", "COURSES");

第一个客户端DataGridView为空,第二个DataGridView填入正确信息

【问题讨论】:

  • 您在两个呼叫中都使用 DG1。
  • 第一次使用表零(DT = DS.Tables[0];)第二次使用表一(DT = DS.Tables[1];)
  • @jdweng 根据文档,Reset 调用应该删除表格。
  • “拖”是指“两个”吗?然后保留两个 DataSources/DataTables; atm 你清除了第一个..
  • 我是否必须为第二个 Datagridview 创建另一个 DataSources/DataTables 变量?

标签: c# database datagridview


【解决方案1】:

我犯了多么愚蠢的错误!我所要做的就是删除 DataSet 和 DataTable 的声明并将其放入函数中,所有冲突都消失了,谢谢(@JohnG,@TaW 以及每个试图提供帮助的成员)

public void LoadData(DataGridView Grid, String fields)
    {
        SetConnection();
        sql_con.Open();
        sql_cmd = sql_con.CreateCommand();
        string CommandText = "select " + fields + " from " + table;
        DB = new SQLiteDataAdapter(CommandText, sql_con);
        DataSet DS = new DataSet();
        DataTable DT = new DataTable();
        DB.Fill(DS);
        DT = DS.Tables[0];
        Grid.DataSource = DT;
        sql_con.Close();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多