如何在GridView中选中RadioButtonList的Yes时为TextBox赋值
解决方案
首先修正.aspx页面中的RadioButtonList,添加AutoPostBack="True",确保选中选项时能实时触发后台事件:
<asp:RadioButtonList ID="RbCompleted" runat="server" Text='<%# Bind("Completed") %>' OnSelectedIndexChanged="RbCompleted_SelectedIndexChanged" AutoPostBack="True"> <asp:ListItem>Yes</asp:ListItem> <asp:ListItem>No</asp:ListItem> <asp:ListItem>Pending</asp:ListItem> </asp:RadioButtonList>
然后在后台C#实现RbCompleted_SelectedIndexChanged方法,完成选中"Yes"时的数据库查询和文本框赋值:
protected void RbCompleted_SelectedIndexChanged(object sender, EventArgs e) { // 获取触发事件的RadioButtonList控件 RadioButtonList rbCompleted = (RadioButtonList)sender; // 定位到当前控件所在的GridView行 GridViewRow currentRow = (GridViewRow)rbCompleted.NamingContainer; // 提取当前行的TrainingID(对应GridView中第2列,索引从0开始为1) string trainingID = currentRow.Cells[1].Text; if (rbCompleted.SelectedValue == "Yes") { string connStr = ConfigurationManager.ConnectionStrings["StaffRosterConnectionString"].ConnectionString; string query = "SELECT Hours FROM Training WHERE TrainingID = @TrainingID"; // 使用using自动释放数据库资源 using (SqlConnection dbConn = new SqlConnection(connStr)) using (SqlCommand dbCmd = new SqlCommand(query, dbConn)) { dbCmd.Parameters.Add("@TrainingID", SqlDbType.VarChar).Value = trainingID; try { dbConn.Open(); // 因为TrainingID唯一,用ExecuteScalar直接获取单个结果 object hoursResult = dbCmd.ExecuteScalar(); if (hoursResult != DBNull.Value) { decimal trainingHours = Convert.ToDecimal(hoursResult); // 找到同行的文本框并赋值 TextBox tbHours = (TextBox)currentRow.FindControl("TbHoursCompleted"); tbHours.Text = trainingHours.ToString("n2"); } } catch (Exception ex) { Response.Write($"操作出错:{ex.Message}"); } } } else { // 选中No/Pending时可清空文本框,或保留原有值,按需调整 TextBox tbHours = (TextBox)currentRow.FindControl("TbHoursCompleted"); tbHours.Text = string.Empty; } }
原代码的问题说明
- 事件时机错误:原
GridView1_RowDataBound是行数据绑定时触发,无法响应RadioButton的选中变更操作。 - 控件定位错误:通过
GridView1.SelectedRow无法正确获取当前编辑行的TrainingID,需从触发事件的RadioButton所在行提取。 - 缺少自动回发:未设置
RadioButtonList的AutoPostBack="True",导致选中选项后不会触发后台事件。 - 资源管理不当:未使用
using语句管理数据库连接,可能造成连接泄漏。
内容的提问来源于stack exchange,提问作者David Megnin
相关产品推荐
相关产品推荐

