You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP GridView数据存入DataTable时获取空值的原因排查

问题:GridView提交时获取文本框值为空的原因及解决办法

这事儿我熟!你遇到的空值问题,核心原因是你用错了获取输入控件值的方式——GridView的Cells[index].Text只能拿到单元格里的静态文本内容,比如你第一列的Label文本,但对于<input>或者ASP.NET TextBox这类可输入控件,用户输入的值根本不在Cell的Text属性里,得通过FindControl找到对应的服务器控件才能拿到真实输入值。

具体原因拆解:

  • 你的txtAgriGridProduction是带runat="server"的HTML输入框,它本质是HtmlInputText服务器控件,用户输入的内容存在它的Value属性里,而非Cell的Text。
  • 就算是ASP.NET原生的TextBox(比如txtAgriGridCultivatedLand),也得通过FindControl定位控件后取Text属性,直接用Cell.Text拿不到用户输入。
  • 另外还要排查一个常见坑:如果你的GridView在Page_Load里每次回发都重新绑定数据,那用户输入的值会被绑定的初始值覆盖,导致你拿到空或者默认值。

修复后的提交按钮代码

把你原来的foreach逻辑改成这样,通过FindControl获取控件值:

DataTable agricrops_dt = new DataTable();
agricrops_dt.Columns.Add(new DataColumn("CROPS", typeof(string)));
agricrops_dt.Columns.Add(new DataColumn("PRODUCTION", typeof(int)));
DataRow drow = null;

foreach (GridViewRow gr in AgriGrid.Rows)
{
    drow = agricrops_dt.NewRow();
    
    // 稳妥获取Crops标签文本:用FindControl比依赖Cell索引更可靠(列顺序变了也不影响)
    Label lblCrop = gr.FindControl("lblcropsagrigrid") as Label;
    if (lblCrop != null)
    {
        drow["CROPS"] = lblCrop.Text;
    }
    
    // 获取生产数量输入框的值
    HtmlInputText txtProduction = gr.FindControl("txtAgriGridProduction") as HtmlInputText;
    if (txtProduction != null && !string.IsNullOrWhiteSpace(txtProduction.Value))
    {
        drow["PRODUCTION"] = int.Parse(txtProduction.Value);
    }
    else
    {
        // 处理空输入的情况,比如默认设为0
        drow["PRODUCTION"] = 0;
    }
    
    agricrops_dt.Rows.Add(drow);
}

额外注意事项

  1. 避免回发时覆盖输入值:确保GridView只在首次加载时绑定数据,回发时不重复绑定,在Page_Load里加判断:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // 这里写你的GridView绑定逻辑,比如BindAgriGrid();
    }
}
  1. 命名空间引用:如果使用HtmlInputText,需要在代码文件顶部添加命名空间引用:
using System.Web.UI.HtmlControls;
  1. 优先用控件ID而非Cell索引:依赖Cell索引(比如gr.Cells[1])很脆弱,后续修改GridView列顺序就会出错,用控件ID通过FindControl定位是更稳健的做法。

内容的提问来源于stack exchange,提问作者nischalinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:43:05