简体   繁体   中英

ASP C# GridView Update SQL Database from Edited Value

I'm struggling with this code. I have a gridview that has a visible column and non-visible column ( Visible="False" ). The non-visible column is a system value, so I'd rather not show the user.

 <asp:TemplateField HeaderText="Del. Qty">
     <ItemTemplate>
          <%# Eval("QUANTITY")%>
     </ItemTemplate>
     <EditItemTemplate>
          <asp:TextBox runat="server" ID="txtQuantity" Text='<%# Eval("QUANTITY")%>' />
     </EditItemTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="System ID" Visible="False">
     <ItemTemplate>
          <%# Eval("SYS_ID")%>
     </ItemTemplate>
     <EditItemTemplate>
          <asp:TextBox runat="server" ID="txtSys" Text='<%# Eval("SYS_ID")%>' />
     </EditItemTemplate>
 </asp:TemplateField>

The C# code:

protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
    var row = GridView2.Rows[e.RowIndex];
    var txtQuantity = (TextBox) row.FindControl("txtQuantity");
    var txtSys = (TextBox) row.FindControl("txtSys");

    var qty = Convert.ToDecimal(txtQuantity.Text);
    var sysId = txtSys.Text;

    UpdateProduct(qty, sysId);
}

While Debugging, I noticed the problem is txtSys constantly shows as NULL . How can I make the value of the SYS_ID not visible to the user, yet usable in the update statement?

When you use Visible=false , the column is not rendered into the gridview. So when you try using row.FindControl , it will return NULL, since the controls doesn't really exist.

Instead of using Visible=false , surrond the item with a DIV which has no visibility:

<EditItemTemplate>
    <div style="visibility:hidden;">
       <asp:TextBox runat="server" ID="txtSys" Text='<%# Eval("SYS_ID")%>' />
    </div>
</EditItemTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM