直接使用数据库设置绑定网格视图的关键列信息以执行 CRUD?更新问题

set Key column info of binded grid view directly with database to perform CRUD? updation issue

我在设计器中创建了数据集,然后我用它来绑定 win-forms 中的 grid-view 控件,这是 datagridview 我的绑定成功了,我也成功地执行了插入,但问题出在更新和删除中 这是我加载和绑定数据的代码

     public void load() {
         dataGridView1.DataSource = null;          
        ds = new DataSet1();
        table = ds.Tables[ds.Customer.TableName];
        ad = new DataSet1TableAdapters.CustomerTableAdapter();
        ad.Adapter.AcceptChangesDuringUpdate = true;
        ad.Adapter.AcceptChangesDuringFill = true;
        DataColumn[] PK_Column = new DataColumn[1];
        DataColumn dc = new DataColumn("cmpid", Type.GetType("System.String"));
        PK_Column[0] = dc;
        dc.AutoIncrement = false;
        ad.GetData(); 
        ad.Adapter.Fill(ds.Customer);
       // ds.Tables[0].PrimaryKey = PK_Column;
        dataGridView1.DataSource = ds.Customer;
    }

但是在单元格值更改事件中我希望它更新数据库,但它不起作用我正在检查调试数据集中绑定的值也已更改但保存未保存在数据库中 whyprivate void

 private void dataGridView1_RowValidated(object sender,  DataGridViewCellEventArgs e)
    {
        SqlCommandBuilder cb;
        DataTable dt = new DataTable();
        table = ((DataTable)dataGridView1.DataSource).GetChanges();
        if (ds != null)
        {
            cb = new SqlCommandBuilder(ad.Adapter);
            ad.Adapter.UpdateCommand = cb.GetUpdateCommand(true);
            ad.Adapter.Update(dt);
        }

   }

为什么这里插入成功,更新、删除却不成功

原因:

Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

在加载函数中设置关键列信息();

试试这个;

GetChanges() 方法适用于行事件,所以我使用了 datagridRowValidated 事件。)

 private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e){
            SqlCommandBuilder cb;
            dt = new DataTable();
            dt = ((DataTable)dataGridView1.DataSource).GetChanges();
            if (ds != null)
            {
                cb = new SqlCommandBuilder(adp);
                adp.UpdateCommand = cb.GetUpdateCommand(true);
                adp.Update(dt);
            }

}

更新 1;

无需任何主键的另一种方法,

string newValue = "";
SqlCommand cmd;
string oldValue = "";

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
      oldValue = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); // store old value to add where 
}

在更改单元格值时,我们将以我认为的动态方式更新数据库(如果更好或有任何建议请通知我。)

  private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        SqlConnection c = new SqlConnection("Data Source=.;Initial Catalog=localdb;Persist Security Info=True;User ID=sa;Password=123");
        if (c.State != ConnectionState.Open)
        {
            c.Open();
        }
        string command = "";
        string columns = "";
        string columnName = dataGridView1.Columns[e.ColumnIndex].Name; // get column name of edited cell
        if (dataGridView1.Columns.Count != 1) // If there is only one column we dont have any where comparison, so we need oldValue of cell (we took value at cellbeginedit event)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (i != e.ColumnIndex)
                {
                    columns += dataGridView1.Columns[i].Name + " = '" + dataGridView1.Rows[e.RowIndex].Cells[i].Value.ToString() + "' "; // compare statement according to other cells (assume that we don't have PK)
                }
                if ((i != dataGridView1.Columns.Count - 1) && (i != e.ColumnIndex))
                {
                    columns += " and ";

                }
            }
            command = "Update "+ ds.Customer.TableName +" set " + columnName + "=@newValue where " + columns;
        }
        else
        {
            command = "Update  " + ds.Customer.TableName + "  set  " + columnName + "=@newValue where ColumName=" + "'" + oldValue + "'";
        }
        newValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); //our new parameter.
        cmd = new SqlCommand(command, c);
        cmd.Parameters.AddWithValue("@newValue", newValue);
        cmd.ExecuteNonQuery();
        c.Close();

}

希望有所帮助,