简体   繁体   English

如何从Datagridview C#更新数据库

[英]How to update DB from Datagridview c#

How to update DB from Datagridview c# ? 如何从Datagridview c#更新数据库? My project is work for load data table in DB.but can't update into DB It's load data button 我的项目适用于数据库中的加载数据表,但无法更新到数据库中。它是加载数据按钮

private void button2_Click(object sender, EventArgs e)
{
        string connectionString;

        connectionString = "Server=localhost;User Id=root; Password=1234; Database=db2; Pooling=false;CharSet=tis620;";
        connection = new MySqlConnection(connectionString);
        sda = new MySqlDataAdapter("Select * from data Where Id = '" + comp.Text.Trim() + "'", connection);

        dt = new DataTable();
        sda.Fill(dt);
        Table1.DataSource = dt;

}

and update button 和更新按钮

private void button3_Click(object sender, EventArgs e)
{

        cmdbl = new MySqlCommandBuilder(sda);

        sda.Update(dt);
        MessageBox.Show("Save data complete");

}

I follow this clip Insert,Delete and Update data in database from datagridview and i can't do it Sorry for my english I speak not good enough and thank you for answer. 我按照这个剪辑从datagridview中插入,删除和更新数据库中的数据 ,但我做不到。对不起,我的英语我说得还不够好,谢谢您的回答。

Assuming you have UpdateCommand configured. 假设您已配置UpdateCommand。 try dt.AcceptChanges() after update 更新后尝试dt.AcceptChanges()

private void button3_Click(object sender, EventArgs e)
{

    cmdbl = new MySqlCommandBuilder(sda);

    sda.Update(dt);
    dt.AcceptChanges()
    MessageBox.Show("Save data complete");

  }

Otherwise follow the MSDN 否则,请遵循MSDN

As a minimum requirement, you must set the SelectCommand property in order for automatic command generation to work. 最低要求是,必须设置SelectCommand属性,以便自动命令生成起作用。 The table schema retrieved by the SelectCommand property determines the syntax of the automatically generated INSERT, UPDATE, and DELETE statements. 由SelectCommand属性检索的表模式确定自动生成的INSERT,UPDATE和DELETE语句的语法。 The DbCommandBuilder must execute the SelectCommand in order to return the metadata necessary to construct the INSERT, UPDATE, and DELETE SQL commands. DbCommandBuilder必须执行SelectCommand才能返回构造INSERT,UPDATE和DELETE SQL命令所需的元数据。 As a result, an extra trip to the data source is necessary, and this can hinder performance. 结果,有必要额外访问数据源,这可能会影响性能。 To achieve optimal performance, specify your commands explicitly rather than using the DbCommandBuilder. 为了获得最佳性能,请显式指定命令,而不要使用DbCommandBuilder。 The SelectCommand must also return at least one primary key or unique column. SelectCommand还必须至少返回一个主键或唯一列。 If none are present, an InvalidOperation exception is generated, and the commands are not generated. 如果不存在,则会生成InvalidOperation异常,并且不会生成命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM