点击按钮时如何将ModalPopupExtender的值传递到GridView页脚文本框
解决ModalPopupExtender中ListBox值传递到GridView页脚TextBox的崩溃问题
看起来你在ASP.NET里用ModalPopupExtender传递ListBox值到GridView页脚TextBox时遇到了崩溃问题,我之前也碰到过类似的情况,大概率是控件获取或者回发生命周期的问题,给你两个可行的解决方案,分别是前端无回发和后端回发的方式,你可以试试:
方案一:前端jQuery无回发传递(避免回发崩溃)
这种方式不需要触发页面回发,直接用JS把选中值传到目标TextBox,还能避免回发带来的GridView状态重置问题。
首先修改弹出层的Done按钮,让它先执行JS再关闭模态框:
<asp:Button ID="btnSupplierDone" runat="server" Text="Done" OnClientClick="transferSelectedValue(); return false;" />
然后添加下面的JavaScript函数(放在页面的<script>标签里):
function transferSelectedValue() { // 获取ListBox的选中项(文本或值,按需选择) var listBox = $('#<%= lst_PdfViewers.ClientID %>'); var selectedText = listBox.find('option:selected').text(); var selectedValue = listBox.find('option:selected').val(); // 获取GridView页脚的TextBox(替换成你的GridView实际ID) var footerTextBox = $('#<%= ((TextBox)GridView1.FooterRow.FindControl("AddSupplierName")).ClientID %>'); // 给TextBox赋值 footerTextBox.val(selectedText); // 想用值的话就改成selectedValue // 关闭模态框 $find('<%= ModalPopupExtenderSupplier.ClientID %>').hide(); }
⚠️ 注意:
- 把
GridView1换成你实际的GridView服务器ID - 确保GridView的
ShowFooter属性设置为true,不然FooterRow会是null导致JS报错
方案二:后端C#回发传递(处理控件获取逻辑)
如果必须用回发方式,那就要解决回发时控件找不到的问题,同时用try-catch捕获异常避免崩溃:
首先修改ModalPopupExtender,添加OkControlID绑定Done按钮:
<act:ModalPopupExtender ID="ModalPopupExtenderSupplier" CancelControlID="SupplierPopupCancel" TargetControlID="Sample" PopupControlID="Pnl_Pdfviewers" OkControlID="btnSupplierDone" runat="server" Enabled="true"> </act:ModalPopupExtender>
然后在btnSupplierDone_Click事件里写安全的控件获取逻辑:
protected void btnSupplierDone_Click(object sender, EventArgs e) { try { // 先判断ListBox是否有选中项 if (lst_PdfViewers.SelectedItem != null) { string selectedContent = lst_PdfViewers.SelectedItem.Text; // 或者用.Value // 获取GridView页脚行 GridViewRow footerRow = GridView1.FooterRow; if (footerRow != null) { TextBox txtSupplier = (TextBox)footerRow.FindControl("AddSupplierName"); if (txtSupplier != null) { txtSupplier.Text = selectedContent; } else { // 提示找不到TextBox,避免崩溃 ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('找不到页脚输入框');", true); } } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('GridView未启用页脚,请检查ShowFooter属性');", true); } } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('请先选择一个选项');", true); } } catch (Exception ex) { // 捕获所有异常,提示错误信息,避免程序直接崩溃 ClientScript.RegisterStartupScript(this.GetType(), "error", $"alert('操作出错:{ex.Message}');", true); // 也可以把错误写入日志方便排查 } }
⚠️ 关键注意点:
- GridView的
ShowFooter必须设为true,否则FooterRow会是null - 不要在
Page_Load里每次都绑定GridView,要放在!IsPostBack判断里,不然回发时GridView会重新生成行,导致页脚控件引用失效 - 给
Pnl_Pdfviewers加上runat="server",确保回发时模态框里的控件状态能被正确保存
常见崩溃原因排查
- 控件ID错误:ASP.NET会给服务器控件生成带前缀的客户端ID,JS里直接用服务器ID会找不到控件,必须用
ClientID获取真实客户端ID - 页脚行不存在:GridView未开启ShowFooter,或者回发时GridView重新绑定导致页脚行被重置
- 未捕获异常:代码里没有try-catch,一旦控件获取失败就直接抛出异常导致崩溃
内容的提问来源于stack exchange,提问作者Programmermid
相关产品推荐
相关产品推荐

