我想为我的用户提供一个数据表,他/她可以在其中编辑数据。 我使用这种方法从sql server
获取数据 public static List<TestAsfa> GetRecordsMan() {
using (var d = new TestEntities())
{
return d.TestAsfa.ToList();
}
当我想写删除功能
时,我卡住了 protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();
int id =Convert.ToInt32(GridView1.Rows[e.RowIndex].ID);
FillGridView();
}
catch
{
Response.Write("<script> alert('Record not deleted...') </script>");
}
}
这是删除功能。我写了下面的方法
public static void deleteRecord(int id)
{
using (var d = new TestEntities())
{
TestAsfa tb = d.TestAsfa.SingleOrDefault(t => t.ID == id);
d.TestAsfa.Remove(tb);
d.SaveChanges();
}
}
但我不知道它没有从发件人那里获得正确的行ID 我不明白我的错误
答案 0 :(得分:0)
要删除所选行,请使用此代码
using(var d = new TestEntities())
{
d.TestAsfa.Remove(d.TestAsfa.Find(id));
d.SaveChanges();
}
或使用此
using(var d = new TestEntities())
{
TestAsfa tb = d.TestAsfa.SingleOrDefault(t => t.Id == id);
d.TestAsfa.Remove(tb);
d.SaveChanges();
}
答案 1 :(得分:0)
不要忘记防止您需要确保您正在检查的ID是实际项目的错误。像这样的东西,例如:
public static void deleteRecord(TestAsfa TA,int id)
{
using(var d = new TestEntities())
{
TA= d.TestAsfa.Where(item => item.ItemId == id).FirstOrDefault();
if (itemTA!= null) {
d.TestAsfa.Remove(TA);
}
}
}
答案 2 :(得分:0)
嗨,试试看看这个
protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteid = (Label)row.FindControl("lblID");
conn.Open();
SqlCommand cmd = new SqlCommand("delete FROM tableName where
id='"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString())+"'", conn);
cmd.ExecuteNonQuery();
conn.Close();
gvbind();
}