数据表不会更新回 sql

本文关键字:sql 更新 数据表 | 更新日期: 2023-09-27 18:34:18

我有两个数据网格视图(viewa,viewb)。我通过在 viawb 中单击和编辑将行视图传递给视图。我可以从服务器获取要查看的项目,但我无法更新数据表。目前我正在尝试用一个 dgv 使用它。如果您至少可以指导我,请表示感谢。

                public Form1()
    {
        InitializeComponent();
    }
    SqlCommand command = new SqlCommand();
    DataTable data = new DataTable();
    private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "server=server.server.com;user=testuser;pwd=password;database=test";
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandText = "select * from malzeme";
        DataTable data = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(data);
        dataGridView1.DataSource = data;
    }
    private void save_Click(object sender, EventArgs e)
    {
        try
        {
            string connectionString= "server=server.server.com;user=testuser;pwd=password;database=test";

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.UpdateCommand = new SqlCommand("UPDATE malzeme SET malzemekodu=@malzemekodu " + "WHERE Id=@Id", conn);
                adapter.Update(data);
            }
           }

        catch
        {
        }
    }
}

这是DGV https://i.stack.imgur.com/7whSK.png 的例子

数据表不会更新回 sql

从您提供的不完整代码来看,您似乎没有定义 SqlDataAdapter 的 InsertCommand/UpdateCommand/DeleteCommand 属性。如果你不告诉它如何更新你的数据库,它就不知道怎么做......以下链接将帮助您更好地了解如何使用 SqlDataAdapter 更新数据库:http://support.microsoft.com/kb/308055 。祝你好运!

编辑您需要在命令文本中填充参数:

using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("UPDATE malzeme SET malzemekodu=@malzemekodu WHERE Id=@Id", conn);
    //  Add parameters to the command to replace the parameter tokens in your command text
    cmd.Parameters.Add(new SqlParameter("@malzemekodu", "someValue"));
    cmd.Parameters.Add(new SqlParameter("@Id", "someId"));
    adapter.UpdateCommand = cmd; 
    adapter.Update(data);
}