【问题标题】:Asp.net grid view template fields data persistAsp.net 网格视图模板字段数据保持不变
【发布时间】:2016-11-07 18:36:27
【问题描述】:

我有一个网格视图,其中包含 4 个模板字段,每个字段都包含一个文本框。

现在我已将这些模板字段与数据源绑定。当我作为用户在文本框中输入一些数据并单击保存按钮(不是 gridview 的一部分而是 webform 中的单个按钮)时,我无法获取单击事件处理程序中的值在文件后面的代码中。请帮帮我。

ASPX 文件

<asp:TemplateField HeaderText="col1"> 
    <ControlStyle Height="25px" Width="60px" />
      <ItemTemplate>
            <asp:TextBox ID="txt1" runat="server" Text='<%# Bind("[col1]") %>'>   
            </asp:TextBox>                 
      </ItemTemplate>
  </asp:TemplateField>

<asp:TemplateField HeaderText="col2">  
  <ControlStyle Height="25px" Width="60px" />
    <ItemTemplate>
      <asp:TextBox ID="txt2" runat="server"  Text='<%# Bind("[col2]") %>'>  
      </asp:TextBox>
    </ItemTemplate>
 </asp:TemplateField>

<asp:TemplateField HeaderText="col3"> 
  <ControlStyle Height="25px" Width="60px" />
    <ItemTemplate>
      <asp:TextBox ID="txt3" runat="server"  Text='<%# Bind("[col3]") %>'>
      </asp:TextBox>
    </ItemTemplate>
 </asp:TemplateField>

<asp:TemplateField HeaderText="col4"> 
  <ControlStyle Height="25px" Width="60px" />
    <ItemTemplate>
      <asp:TextBox ID="txt4" runat="server"  Text='<%# Bind("[col4]") %>'>
      </asp:TextBox>
    </ItemTemplate>       
</asp:TemplateField>

文件隐藏代码

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvEdit.Rows)
    {
            string a = ((TextBox)row.FindControl("col1")).Text;
                 //above line gives a null value
    }
}

【问题讨论】:

  • 您可能还需要添加 HTML

标签: c# asp.net gridview templatefield


【解决方案1】:

您需要遍历GridViewRowCollection,然后对于每一行,通过您在标记中提供的Id 找到控件。例如:

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvEdit.Rows)
    {
        var txt1 = row.FindControl("txt1") as TextBox;
        var txt2 = row.FindControl("txt2") as TextBox;
        var txt3 = row.FindControl("txt3") as TextBox;
        var txt4 = row.FindControl("txt4") as TextBox;

        // access the Text property of each, e.g. txt1.Text
    }
}

更新:确保当您进行数据源绑定时,它只发生在初始加载而不是后续回发时,否则每次都会重置您的更改。

protected void Page_Load(object sender, EventArgs e) 
{
    if (!IsPostBack)
    {
        GridView1.DataSource = // data source
        GridView1.DataBind();
    }
}

【讨论】:

  • 没有。它不起作用。如果我提供来自数据源的值,则返回相同的值,但如果我在文本框中(作为用户)修改 dat,它只返回数据源中的数据
  • @user3107338 我还没有看到数据绑定逻辑,但请确保它仅在初始加载时发生。查看更新的答案。
  • 哇。忘了把那个回邮条件。非常感谢 lottttttt 的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 2014-05-21
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2016-03-20
  • 2018-05-18
相关资源
最近更新 更多