c# - 如何使用 C# 读取 gridview 中动态添加的文本框值?

标签 c# asp.net

我想在 GridView 的每个单元格中使用 TextBox 动态添加行和列。我已经成功地做到了这一点。但问题是,当我点击一个按钮时,我无法读取 TextBox 的值。

<asp:GridView runat="server" ID="gv" OnRowDataBound="gv_OnRowDataBound"></asp:GridView>

在网格中动态添加行和列:

protected void btnGenerate_OnClick(object sender, EventArgs e)
{
    int rowsCount = Convert.ToInt32(tbxRow.Text);
    int colsCount = Convert.ToInt32(tbxCol.Text);
    DataTable dt=new DataTable();
    for(int col=0;col<colsCount;col++)
    {
        dt.Columns.Add("D-" + col, typeof (int));
    }
    for (int i = 0; i < rowsCount; i++)
    {
        DataRow dr = dt.NewRow();
        dt.Rows.Add(dr);
    }
    gv.DataSource = dt;
    gv.DataBind();
}

这是我将文本框添加到 GridView 的代码:

protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            TextBox txt = new TextBox();
            txt.ID = "tbx" + i;
            e.Row.Cells[i].Controls.Add(txt);
        }
    }
}

我试过这个来获取文本框的值,但它总是显示为空:

protected void btnSave_OnClick(object sender, EventArgs e)
{
    foreach (GridViewRow row in gv.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 0; i < row.Cells.Count; i++)
            {
                TextBox tb = (TextBox) row.Cells[i].FindControl("tbx" + i);
            }

        }
    }
}

最佳答案

您必须将它们添加到 OnRowCreated 中,它不仅在您对网格进行数据绑定(bind)时还会在每次回发时触发:

protected void gv_OnRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            TextBox txt = new TextBox();
            txt.ID = "tbx" + i;
            e.Row.Cells[i].Controls.Add(txt);
        }
    }
}

所以你必须使用初始化并将它们添加到 RowCreated 中,如果你想分配一个文本,则使用 RowDataBound

但为什么不使用 TemplateField 并在其中添加文本框。这会让您的生活更轻松。

旁注:您不需要 DataControlRowType.DataRow - 检查您是否枚举 Rows - 网格的属性,因为只有 DataRow-返回项目:

protected void btnSave_OnClick(object sender, EventArgs e)
{
    foreach (GridViewRow row in gv.Rows)
    {
        for (int i = 0; i < row.Cells.Count; i++)
        {
            TextBox tb = (TextBox) row.Cells[i].FindControl("tbx" + i);
        }
    }
}

关于c# - 如何使用 C# 读取 gridview 中动态添加的文本框值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37156422/

相关文章:

c# - 如何编辑所有特殊 html 标签的属性(如 a)

c# - microsoft azure - 获取目录完整路径

c# - 非方形螺旋矩阵打印不正确

c# - 警报消息框

c# - WPF 如何在代码隐藏的 Gridview 绑定(bind)中设置复选框

c# - 从服务在事件用户 session 中启动程序?

asp.net - 增加 div 高度以适应 ajax Accordion

javascript - 如何处理 ASP .NET Api HTTPResponseMessage 来下载文件

html - 将 TD 扩展到最大可用宽度

c# - 使用 HttpPost 方法提交表单后 ASP.NET Core 重定向到同一页面