Datatable没有更新回sql

时间:2013-10-06 13:02:40

标签: c# sql sql-server datatable

我有两个datagridview(viewa,viewb)。我通过点击并编辑viawb将行viewa传递给viewb。我可以从服务器获取查看项目,但我无法更新数据表。目前我正在尝试使用一个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 http://i.imgur.com/bQn4hZV.png

的示例

1 个答案:

答案 0 :(得分:0)

根据您提供的不完整代码,您似乎没有定义SqlDataAdapter的InsertCommand / UpdateCommand / DeleteCommand属性。如果您没有告诉它如何更新您的数据库,它就不知道如何......这里有一个链接可以帮助您更好地了解如何使用SqlDataAdapter更新您的数据库:{{3 }。祝你好运!

修改 您需要在命令文本中填充参数:

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);
}