首页 > 解决方案 > 在 Asp.Net 中单击 GridView 中的添加按钮时,如何在下拉列表中删除先前选定的项目

问题描述

单击gridview asp.net,如何删除下拉添加按钮中的最后一行选定项目。

GridViewRow gvrow = (GridViewRow)((Control)e.CommandSource).NamingContainer;
if (e.CommandName == "Add")
{
    ddt = CreateDt();
    int j = 0;
    foreach (GridViewRow gr in GvPatientAccomDtls.Rows)
    {
        ddt.Rows.Add();
        ddt.Rows[j]["TreatmentCode"] = ((DropDownList)gr.FindControl("ddlTreatment")).SelectedValue;
        ddt.Rows[j]["Days"] = ((TextBox)gr.FindControl("txtDays")).Text;
        ddt.Rows[j]["Cost"] = ((TextBox)gr.FindControl("txtCost")).Text;
        j++;
    }
    ddt.Rows.Add();
    GvPatientAccomDtls.DataSource = ddt;
    GvPatientAccomDtls.DataBind();
}

标签: asp.netsql-serverc#-4.0

解决方案


您可以使用RowDataBound事件处理

void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
  if(e.Row.RowType == DataControlRowType.DataRow)
  {
    var thisRow = (DataRowView)e.Row.DataItem;
    var source = thisRow.DataView;
    var lastRowIndex = e.Row.DataItemIndex -1;
    DataRowView lastRow = null;
    var ddl = (DropDownList)e.Item.FindControl("ddl");
    DropDownList ddlLast = null;
    if(lastRowIndex>=0){
        lastRow = source[lastRowIndex];
        ddlLast = (DropDownList)((GridView)sender).Rows[lastRowIndex].FindControl("ddl");
        //remove the items of this ddl according to the items of the last dll
    }
  }
}

推荐阅读