自从我尝试编程之后已经有一段时间了。我一直在DGV和数据库上练习基本的CRUD。我已经得到了我的" ADD / CREATE"功能正常,但我的删除似乎不起作用。
这是一个截图:
http://oi61.tinypic.com/29fblky.jpg
编辑: 在这里发布代码;这是我工作的ADD / CREATE函数:
private void btnAdd_Click(object sender, EventArgs e)
{
connectionstring = "server=" + server + ";" + "database=" + database +
";" + "uid=" + uid + ";" + "password=" + password + ";";
con = new MySqlConnection(connectionstring);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select * from testdatabase", con);
DataSet ds = new DataSet();
da.Fill(ds);
testTable1.DataSource = ds.Tables[0];
con.Close();
// now instead of these next 4 lines
DataRow row = ds.Tables[0].NewRow();
row[0] = tbID.Text;
row[1] = tbName.Text;
ds.Tables[0].Rows.Add(row);
// ds.Tables[0].Rows.RemoveAt(testTable1.CurrentCell.RowIndex);
// is what i used to delete
// what did i do wrong?
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
da.UpdateCommand = cb.GetUpdateCommand();
da.Update(ds);
((DataTable)testTable1.DataSource).AcceptChanges();
}
答案 0 :(得分:0)
如果要在单击按钮后删除行,可以按照此伪代码进行操作。
之后,您可以从网格中删除当前行并通知 操作所在的基础数据源 完成。(AcceptChanges的)
private void btnDelete_Click(object sender, EventArgs e)
{
// No row to delete?
if(testTable1.CurrentRow == null)
return;
// Get the cell value with the primary key
int id = Convert.ToInt32(testTable1.CurrentRow.Cells[0].Value)
// Start the database work...
connectionstring = .....;
using(con = new MySqlConnection(connectionstring))
using(cmd = new MySqlCommand("DELETE FROM testdatabase where id = @id", con))
{
con.Open();
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
// Fix the grid removing the current row
testTable1.Rows.Remove(testTable1.CurrentRow);
// Fix the underlying datasource
((DataTable)testTable1.DataSource).AcceptChanges();
}
}