0

我有两个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的示例

4

1 回答 1

0

从您提供的不完整代码来看,您似乎没有定义 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);
}
于 2013-10-06T13:22:52.980 回答