【问题标题】:How can I call "delete row " event when i click on "edit" button in gridview? asp.net C#单击gridview中的“编辑”按钮时,如何调用“删除行”事件? ASP.NET C#
【发布时间】:2016-08-07 09:57:07
【问题描述】:

我有一个gridview,我希望当我单击gridview 中的“编辑”按钮时,编辑插入到gridview 之外的控件中的行值,然后删除行。我可以在“编辑”事件中调用“删除”事件方法吗,因为我想先检索控件中的值,然后删除行。

这是我的 aspx.cs 代码。在此处删除和编辑事件代码:

protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    DataTable t = (DataTable)Session["MyDataTable"];
    t.Rows.RemoveAt(e.RowIndex);
    GridView2.DataSource = t;
    GridView2.DataBind();
}

public void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
    DataTable t = (DataTable)Session["MyDataTable"];
    TextBox1.Text=GridView2.Rows[e.NewEditIndex].Cells[1].Text.ToString();

    DropDownList1.Text = GridView2.Rows[e.NewEditIndex].Cells[2].Text.ToString();
    GridView2.EditIndex = -1;
    GridView2.DataSource = t;
    GridView2.DataBind();

    //CAN I CALL GRIDVIEW_ROW_DELETING method here? I try but problem is arguments etc
}

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    正如 Emanuaele 所说,有更好的方法可以做到这一点,但如果你想让你的代码接近你所拥有的,请将你的删除代码移动到一个单独的方法中

    protected void DeletingRow(int rowIndex)
    {
        DataTable t = (DataTable)Session["MyDataTable"];
        t.Rows.RemoveAt(rowIndex);
        GridView2.DataSource = t;
        GridView2.DataBind();
    }
    

    然后 GridView2_RowDeleting 将更改为

    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DeletingRow(e.RowIndex);
    }
    

    GridView2_RowEditing 将更改为

    public void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        DaTable t = (DataTable)Session["MyDataTable"];
        TextBox1.Text=GridView2.Rows[e.NewEditIndex].Cells[1].Text.ToString();
        DropDownList1.Text =   GridView2.Rows[e.NewEditIndex].Cells[2].Text.ToString();
        GridView2.EditIndex = -1;
        GridView2.DataSource = t;
        GridView2.DataBind();
        //CAN I CALL HERE GRIDVIEW_ROW_DELETING METHOD,I try but problem is arguemnts etc
    
        DeletingRow(e.NewEditIndex);
    }
    

    【讨论】:

    • @March 感谢您的回答,但是出现了一个红线错误。在“Gridview2_RowEditing”错误出现在最后一行 DeletingRow(GridView2.RowIndex); //在RowIndex,因为方法包含GridViewEditEventArgs e pass
    • 不包含行索引的定义
    • 抱歉应该是 CurrentRow.Index
    • 我现在检查它,但它不起作用,这是快照hostthenpost.org/uploads/2343991ab460f29ec78fea625b680e43.png
    • 可能是 e.NewEditIndex 但它不正确!最好使用 RowCommand
    【解决方案2】:

    如果数据来自数据库,则方法是错误的。 您必须处理数据,而不是页面控件(可以,但最好不要这样做)。

    不要用Session来存储Datatable(里面有多少条记录?)

    使用按钮的CommandArgument 获取记录的ID。 从数据库中检索记录并将字段存储在控件中。单击一个按钮,保存数据,删除记录并重新绑定。

    使用您的方法,您可以将删除事件的代码移动到私有方法中并从编辑事件中调用它

    【讨论】:

    • 我现在不想要任何数据库连接..Actaully 我的想法是首先用户将值插入gridview,然后按下按钮“创建表”然后将所有值插入数据库..首先告诉我pelase,我可以在编辑事件中调用删除事件方法吗?
    • 阅读马克的回答
    猜你喜欢
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2011-10-07
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多