【问题标题】:Can't retrieve new value from GridView template field无法从 GridView 模板字段中检索新值
【发布时间】:2015-06-08 05:00:39
【问题描述】:

我无法检索在 GridView 的文本框模板字段中输入的新值。

这是我的标记:

<asp:TemplateField HeaderText="username" SortExpression="username">
    <ItemTemplate>
        <asp:Label ID="Label2" runat="server" Text='<%# Bind("username") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtUserName" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
    </EditItemTemplate>
</asp:TemplateField>

这就是我在 GridView 的 RowCommand 事件处理程序中尝试检索新值的方式:

 string userName = ((TextBox)grdUserList.Rows[rowIndex].FindControl("txtUserName")).Text;

当我执行这段代码时,我得到的是旧值而不是新输入的值。

有人知道我错过了什么吗?提前致谢。

【问题讨论】:

  • 你能告诉我们你绑定gridview的代码吗?
  • @Adil 嗨。我刚刚找到了解决我的问题的方法。我搜索并发现在检索过程开始之前正在刷新 GridView,因为我在 Page_Load 方法上重新绑定了 GridView。我通过在回发时(或至少在我进行更改之前)不重新绑定gridview来解决问题。无论如何感谢您的回复:)
  • 我以为您在回发时绑定了 GridView 并丢失了新输入的值。
  • @Adil 我在 Page_Load 中绑定了 gridview。当页面回发时,我不知道 pageLoad 是在 GridView 的 RowCommand 事件之前先执行的。所以我认为发生的事情是gridview的内容(包含新数据)被我的数据库中的原始内容覆盖(执行Page_Load时)所以当我试图在Row_Command处理程序中获取新数据时,我得到了原始内容。请原谅我的英语:D

标签: c# asp.net gridview templatefield


【解决方案1】:

我刚刚找到了解决问题的方法。我搜索并发现在检索过程开始之前正在刷新 GridView,因为我在 Page_Load 方法上重新绑定了 GridView。我通过使用 IsPostback 方法在回发(或至少在我进行更改之前)不重新绑定 gridview 来解决问题。谢谢大家的回复:)

【讨论】:

    【解决方案2】:

    您在错误的 GridView 事件中检索新值。您必须在 GridView 控件中添加 OnRowUpdating="grdUserList_RowUpdating" 事件,然后检索新的 TextBox 值。

    OnRowUpdating 代码隐藏事件:

    protected void grdUserList_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string userName = ((TextBox)grdUserList.Rows[e.RowIndex].FindControl("txtUserName")).Text;
    
        // Write your update query and logic over here.
    }
    

    您可以参考here 获取更多知识。

    如果您有任何问题,请告诉我。

    【讨论】:

      【解决方案3】:
      use this code in gridview    
      
        <Columns>
      
          <asp:TemplateField HeaderText="SrNo">
          <EditItemTemplate>
      
          <asp:TextBox ID="txtsrno" runat="server" Text='<%#Eval("SrNo") %>'>
          </asp:TextBox>
          </EditItemTemplate>
      
      
          <ItemTemplate>
        <asp:Label ID="lblsrno" runat="server" Text='<%#Eval("SrNo") %>'>
          </asp:Label>
      
          </ItemTemplate>
          </asp:TemplateField>
        </Columns>
      

      【讨论】:

        猜你喜欢
        • 2014-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多