【问题标题】:Add lines to Datagridview immediately立即向 Datagridview 添加行
【发布时间】:2021-04-10 14:40:45
【问题描述】:

我有一个 DatagridView,我想向它添加新行。新行应立即出现在 GUI 中。

private void button1_Click(object sender, EventArgs e)
{               
    dataGridView1.DataSource = Class1.ds.Tables[0];
    String str = "INSERT INTO workers(Worker_Id," +
        "Salary, Work_Hours, Worker_Tel, Worker_Name) " + 
        "VALUES('" + Worker_Id_TB.Text + "','" + 
        int.Parse(Salary_TB.Text) + "','" + 
        int.Parse(Work_Hours_TB.Text) + "','" + Tel_TB.Text + "','" +  
        Worker_Name_TB.Text + "')";
    Class1.GetDataSet(str);
}

【问题讨论】:

  • 你能告诉我们你到目前为止做了什么吗?
  • 请提供更详细的代码示例,说明您目前拥有的代码示例。有很多方法可以做到这一点,这一切都取决于到目前为止您所拥有的代码示例,以了解哪种方式可以处理您的代码。
  • 现在为您编辑
  • MS Documentation 网站上有很多很棒的文章,介绍了数据提供者工具的工作原理(没有一篇会显示将数据粘合到字符串中以进行查询)。
  • 向数据表添加 3 行。代码中的 INSERT 查询 a) 无关紧要,并且 b) 容易受到 SQL 注入黑客攻击。阅读bobby-tables.com

标签: c# sql visual-studio datagridview windows-forms-designer


【解决方案1】:

如果您的 Class1 代码正常工作,您可以尝试将 BindingSource 控件添加到包含 DataGridView 的 Windows 窗体。那么,

   bindingSource1.DataSource = Class1.ds.Tables[0];
   
   dataGridView1.DataSource = bindingSource1;

   String str = "INSERT INTO ...  ";

   Class1.GetDataSet(str);  [before executing the sql command in this code, you should probably do "bindingSource1.EndEdit()"]

如果您的 Class1 代码仍未在 DGV 中生成所需的新数据,您可以考虑创建和使用 Fill() 或 InsertQuery() sql 查询,这些查询可以在设计模式下在 DataSet.DataTable 的 DataTableAdapter 中定义。此外,学习以编程方式创建新 DataRow 对象并将其添加到 DataTable 可能会有所帮助。 如果 DGV 数据绑定正确,那么更新数据表也应该更新 dataGridView。

如果您需要更多帮助,请向我们展示 Class1 代码。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多