GridView选中行TextBox内容无法显示问题求助(Quantity字段空白)
解决GridView选中行Quantity字段TextBox内容空白问题
问题出在你直接通过row.Cells[4].Text获取Quantity的值——因为这一列是TextBox控件,单元格的Text属性并不会同步用户输入的内容,必须先找到对应的TextBox控件再读取它的Text属性。
修改后的代码如下:
protected void GetSelectedRecords(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Item"), new DataColumn("Number"), new DataColumn("Name"), new DataColumn("Quantity") }); foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox chkRow = row.Cells[0].FindControl("chkRow") as CheckBox; if (chkRow.Checked) { string item = row.Cells[1].Text; string number = row.Cells[2].Text; string name = row.Cells[3].Text; // 找到Quantity列的TextBox控件,读取用户输入值 TextBox txtQuantity = row.Cells[4].FindControl("txtQuantity") as TextBox; string quantity = txtQuantity?.Text ?? string.Empty; dt.Rows.Add(item, number, name, quantity); } } } gvSelected.DataSource = dt; gvSelected.DataBind(); }
注意事项
- 确保GridView中Quantity列的TextBox控件ID是
txtQuantity,如果你的实际控件ID不同,要替换成对应的名称。 - 使用
?.Text ?? string.Empty是为了避免控件找不到时触发空引用异常,提升代码健壮性。
内容的提问来源于stack exchange,提问作者kimk
相关产品推荐
相关产品推荐

