简体   繁体   English

将命令 C# DataGridView 更新为 SQL

[英]update command C# DataGridView to SQL

I'm attempting to update a SQL table from C# project datagridview "Work_Table".我正在尝试从 C# 项目 datagridview“Work_Table”更新 SQL 表。 However when I attempt to make the update I get this error但是,当我尝试进行更新时,出现此错误

"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'" “更新无法找到 TableMapping ['Work_Table'] 或 DataTable 'Work_Table'”

Any ideas?有任何想法吗?

Here is my code below:这是我的代码如下:

        try
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                string query = @"Select * from person.addresstype";

                SqlCommand cmd = new SqlCommand(query, conn);

                SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                dAdapter.Update(ds, "Work_Table");

                MessageBox.Show("Saved");
            }
        }
        catch (Exception ee)
        {
            MessageBox.Show(ee.Message);

You need to retrieve the DataTable from the .DataSource property of the grid.您需要从网格的.DataSource属性中检索DataTable This will have the information on what was added, updated and deleted.这将包含有关添加、更新和删除内容的信息。

You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.您可以跳过该命令并将选择字符串和连接字符串直接传递给DataAdapter构造函数。

Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update .创建一个CommandBuilder来为DataAdapter.Update提供插入、更新和删除文本。 Pass the DataAdapter to the constructor of the CommandBuilder .DataAdapter传递给CommandBuilder的构造函数。

    private string connString = "Your connection string";
    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)dataGridView1.DataSource;
        try
        {
            using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
            using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
            {
                dAdapter.Update(dt);
            }
            MessageBox.Show("Saved");
        }
        catch (Exception ee)
        {
            MessageBox.Show(ee.Message);
        } 
    }

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

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