当boundfield设置为false时,在编辑Gridview时获取特定列的值

时间:2018-09-20 08:24:28

标签: asp.net gridview datagridview

当boundfield设置为false时,如何在编辑gridview时获取某些特定单元格的值。

<asp:GridView ID="GridViewInvoice" runat="server" ShowHeaderWhenEmpty="true" DataKeyNames="DOID" AutoGenerateColumns="False" CssClass="mGrid" HeaderStyle-CssClass="th" PagerStyle-CssClass="pgr"
    Width="100%" BorderStyle="Solid" Style="overflow: auto" OnRowDataBound="GridViewInvoice_RowDataBound" OnRowEditing="GridViewInvoice_RowEditing" OnRowDeleting="GridViewInvoice_RowDeleting">
    <AlternatingRowStyle BackColor="#CCCCFF" />
    <Columns>
        <asp:BoundField DataField="Tax1" Visible="false" HeaderText="Tax1" SortExpression="Tax1" HeaderStyle-Width="7%" ItemStyle-CssClass="colHidden" HeaderStyle-CssClass="colHidden" ItemStyle-HorizontalAlign="Right" ReadOnly="false" />
    </Columns>
</asp:GridView>

1 个答案:

答案 0 :(得分:0)

如果GridView的可见性设置为BoundField,则无法访问GridView中的Hidden值。而是添加一个HiddenField并在GridView Edit Event中访问它。

将以下内容添加为GridView列

<asp:GridView ID="GridViewInvoice" runat="server" ShowHeaderWhenEmpty="true" DataKeyNames="DOID" AutoGenerateColumns="False" CssClass="mGrid" HeaderStyle-CssClass="th" PagerStyle-CssClass="pgr"
    Width="100%" BorderStyle="Solid" Style="overflow: auto" OnRowDataBound="GridViewInvoice_RowDataBound" OnRowEditing="GridViewInvoice_RowEditing" OnRowDeleting="GridViewInvoice_RowDeleting">
    <AlternatingRowStyle BackColor="#CCCCFF" />
    <Columns>
        <asp:BoundField DataField="Tax1" Visible="false" HeaderText="Tax1" SortExpression="Tax1" HeaderStyle-Width="7%" ItemStyle-CssClass="colHidden" HeaderStyle-CssClass="colHidden" ItemStyle-HorizontalAlign="Right" ReadOnly="false" />
       <asp:HiddenField ID="Tax1" runat="server" Value='<%#Eval("Tax1") %>'/>
    </Columns>
</asp:GridView>

隐藏代码

protected void GridViewInvoice_RowEditing(object sender, GridViewEditEventArgs e)
{
  HiddenField hf = (HiddenField)GridViewInvoice.Rows[e.RowIndex].FindControl("Tax1");

  if (hf != null)
  { 
      var value = hf.Value;
  }  
}

或者,如果您在GridView中指定了一个值,则也可以使用DataKeyNames来获取值。

  

获取或设置一个包含主键名称的数组   GridView控件中显示的项目的字段。

这样的事情,

<asp:GridView ID="GridViewInvoice" runat="server" DataKeyNames="Tax1">
<Columns>
   <asp:HiddenField ID="Tax1" runat="server" Value='<%#Eval("Tax1") %>'/>
</Columns>
</asp:GridView>

然后获取值,

protected void GridViewInvoice_RowEditing(object sender, GridViewEditEventArgs e)
{
    var value = GridViewInvoice.DataKeys[e.RowIndex]["Tax1"].ToString();
}