【问题标题】:Change TextBox data in Gridview (asp net c #)在Gridview中更改TextBox数据(asp net c#)
【发布时间】:2019-02-15 23:59:52
【问题描述】:

我创建了一个 gridview,其中包含在后端填充的文本框:

<asp:GridView ID="grvMyTest" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" Height="30%" TabIndex="9" 
AllowSorting="True" Width="100%" Visible="true" AllowPaging="True" 
PageSize="20" CssClass="mGrid" PagerStyle-CssClass="pgr">
  <Columns>
     <asp:TemplateField HeaderText="Jan">
        <ItemTemplate>
           <asp:TextBox ID="tbjan" runat="server" Text='<%# Eval("mJan") %>' 
              Width="50px" style="text-align: center"></asp:TextBox>
        </ItemTemplate>
      <HeaderStyle BackColor="Control" HorizontalAlign="Center" />
      <ItemStyle HorizontalAlign="Center" />
   </asp:TemplateField>

在后端,我希望当用户单击按钮时,我想检索要在数据库中更新的 TextBox 的值:

<asp:Button runat="server" Text="Alter values" id="testButton" OnClick="clickedButton" />

后端代码:

protected void clickedButton(object sender, System.EventArgs e)
{
  foreach (GridViewRow row in grvMyTest.Rows) //Running all lines of grid
  {
      TextBox value = ((TextBox)(row.Cells[0].FindControl("mJan")));
   }
}

但即使在出现在网格上的数据库中给出了值,该值也始终为空。

当页面加载时,值会出现: Grid 但是,当按钮被点击(clickedButton 方法)时,该值为 null。

【问题讨论】:

  • TextBox value = ((TextBox)(row.FindControl("tbjan")));
  • 谢谢@vdwwd!但是,代码检索在 Bind 中设置的值。我希望它恢复用户更改的内容。例如,单元格的原始值为10,而用户在TextBox中更改为11。当按下按钮时,我想要值 11,而不是 10。

标签: c# asp.net


【解决方案1】:

一个非常快速和简单的解决方案是将标签添加到 GridView 并将其 Visiblity 设置为 false。

<asp:TextBox ID="tbjan" runat="server" Text='<%# Eval("mJan") %>'></asp:TextBox>
<asp:Label ID="tbjanLabel" runat="server" Text='<%# Eval("mJan") %>' Visible="false"></asp:Label>

然后你可以在后面的代码中比较这些值

 TextBox value = (TextBox)(row.FindControl("tbjan"));
 Label lbl = (Label)(row.FindControl("tbjanLabel"));

 if (lbl.Text == value.Text)
 {
     //no change
 }

【讨论】:

  • 这正是她所需要的,非常感谢您的帮助。
【解决方案2】:

补充 VDWWD 响应,确保页面没有调用回发并且缺少来自 gridview 的引用。

【讨论】:

  • 回发较早发生,清除用户插入网格的内容。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多