从代码背后的Gridview中获取Eval值

本文关键字:获取 Eval Gridview 代码 背后 | 更新日期: 2023-09-27 17:59:47

我有一个从具有多个TemplateFields的数据库加载的网格视图。如何从代码隐藏中检索Eval值?换句话说,我需要该列的模板字段名称。

我想获取"Registrations"并将其存储在一个变量中。

<asp:TemplateField HeaderText="REG" SortExpression="Registrations">
     <EditItemTemplate>
            <asp:CheckBox ID="cbRegEdit" runat="server" Checked='<%# (int)Eval("Registrations") == 1 %>' />
     </EditItemTemplate>
     <ItemTemplate>
                <asp:CheckBox ID="cbReg" runat="server" Enabled="false" Checked='<%# (int)Eval("Registrations") == 1 %>'>
                 </asp:CheckBox>
      </ItemTemplate>
      <ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

从代码背后的Gridview中获取Eval值

您必须挂接到OnRowDataBound并执行以下操作:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
  if(e.Row.RowType == DataControlRowType.DataRow)
  {
    var registrations = ((YourType)e.Row.DataItem).Registrations;
    //do something 
  }
}

你的GridView必须是:

<asp:GridView OnRowDataBound="GridView1_RowDataBound" ...

可能最简单的方法是为网格视图分配一个数据键。

一个例子是这样的:

<asp:Gridview ID="gvExample" runat="server" DataKeyNames="Registrations">

然后在代码后面,您只需要行索引,您可以执行以下操作:

gvExample.Datakeys(rowindex).value
            CheckBox CBreg = (Page.FindControl("cbReg") as CheckBox);
            bool Reg = CBreg.Checked;   //Reg value stored

如果无法通过这种方式找到控件,则可能需要将Page.FindControl更改为TemplateField控件ID。