ASP.NET嵌套GridView按钮点击获取子级Dropdownlist值为0问题咨询
问题根因
你遇到的两个问题本质都是页面回发逻辑错误导致的:
- DropDownList选中值始终为0:页面点击按钮触发回发时,你没有在
Page_Load中对父GridView的绑定逻辑加IsPostBack判断,导致回发时父/子GridView被重新绑定,DropDownList的选中状态被初始化重置,自然只能拿到默认值0。 - TextBox取值带前置逗号:多为你存储TextBox值的拼接逻辑存在重复追加逗号的问题,可直接通过字符串处理去除。
解决方案
第一步:修正Page_Load绑定逻辑
给父GridView的绑定逻辑加非回发判断,确保只有页面第一次加载时才绑定GridView,回发时保留用户输入的控件状态:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // 此处放置你原本绑定gv_TrvMainNested的代码 BindMainGridView(); } }
注:子GridView的绑定逻辑是在父GridView的
RowDataBound事件中触发的,父GridView不回发重绑,子GridView自然也不会被重写,DropDownList的选中状态会自动保存在ViewState中,无需额外处理。
第二步:优化取值逻辑
你原有的代码重复查找子GridView多次,效率偏低且容易出错,修改为如下写法,同时处理TextBox前置逗号问题,完全不需要依赖GridView内置事件,直接在外部按钮点击事件中执行即可:
foreach (GridViewRow mainRow in gv_TrvMainNested.Rows) { // 仅查找一次子GridView GridView gvDetail = mainRow.FindControl("gv_TrvDetailNested") as GridView; if (gvDetail == null || gvDetail.Rows.Count == 0) continue; foreach (GridViewRow detailRow in gvDetail.Rows) { // 取值前先判空,避免空引用异常 DropDownList ddlDriver = detailRow.FindControl("gv_DDLDriver") as DropDownList; int driverIndex = ddlDriver?.SelectedItem != null ? Convert.ToInt32(ddlDriver.SelectedValue) : 0; TextBox tbReg = detailRow.FindControl("tb_Reg") as TextBox; string regNo = tbReg != null ? tbReg.Text.TrimStart(',') : string.Empty; TextBox tbRemark = detailRow.FindControl("tb_Remark") as TextBox; string remark = tbRemark != null ? tbRemark.Text.TrimStart(',') : string.Empty; // 你的业务保存逻辑 if (driverIndex > 0 && !string.IsNullOrWhiteSpace(regNo)) { // 执行保存操作 } } }
可选校验点
如果上述操作后DropDownList仍然取不到值,检查两个配置:
- 确认
gv_DDLDriver的绑定逻辑是否在gv_TrvDetailNested_RowDataBound中执行,且没有重复绑定 - 确认父/子GridView、DropDownList控件都没有设置
EnableViewState="false"(默认是开启状态)
内容的提问来源于stack exchange,提问作者Syed Emmad Zia
相关产品推荐
相关产品推荐

