简体   繁体   English

从.net gridview中删除

[英]Deleting from .net gridview

Im looking to programmatically delete from a GridView . 我希望以编程方式从GridView删除。

I have implemented the gridview's OnRowDeleting="Delete_Record" event handler, and this is called when the user clicks the delete link on the GridView, but as the row doesn't seem to be selected the code which does the delete does not work. 我已经实现了gridview的OnRowDeleting="Delete_Record"事件处理程序,当用户单击GridView上的删除链接时调用它,但由于似乎没有选择行,执行删除的代码不起作用。

To test further I can click select, to select the row (commenting out the code behind the select) then if I click delete the code runs fine. 为了进一步测试我可以单击选择,选择行(注释掉选择后面的代码)然后如果我单击删除代码运行正常。

Is there a way to have the row selected as the first step in the Delete_Record ? 有没有办法将行选中作为Delete_Record

GridViewRow row = gvResults.SelectedRow;
string id = row.Cells[1].Text;

ASB_DataDataContext db = new ASB_DataDataContext();
var delCase = from dc in db.Inputts
              where dc.counter == Convert.ToInt32(id)
              select dc;

foreach (var nCase in delCase)
{
    db.Inputts.DeleteOnSubmit(nCase);
    db.SubmitChanges();
}

Since you are using the event you should be having the required index as part of the GridViewDeleteEventArgs e which should be like say e.RowIndex 由于您正在使用该事件,因此您应该将所需的索引作为GridViewDeleteEventArgs e一部分,这应该像e.RowIndex

you can then access your needed parameter as grid.Rows[e.RowIndex].Cells[1].Text 然后,您可以访问所需的参数grid.Rows[e.RowIndex].Cells[1].Text

You can achieve by the code shown below 您可以通过下面显示的代码实现

public void GridView1_Delete_Record (Object sender, GridViewDeleteEventArgs e)
{
    string id = gridView1.Rows[e.RowIndex].Cells[2].Text;

    ASB_DataDataContext db = new ASB_DataDataContext();
    var delCase = from dc in db.Inputts
              where dc.counter == Convert.ToInt32(id)
              select dc;

    foreach (var nCase in delCase)
    {
       db.Inputts.DeleteOnSubmit(nCase);
       db.SubmitChanges();
    }  Message.Text = "";
}  

Set db.Inputts as DataSource of your datagrid. db.Inputts设置为datagrid的DataSource。 Just add next two lines after your code: 只需在代码后添加下两行:

datagridView1.DataSource = null;
datagridView1.DataSource = db.Inputts;

Setting datasource to null is for clearing previous data from datagrid; 将datasource设置为null用于清除datagrid中的先前数据;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM