从模板字段访问GridView数据

本文关键字:GridView 数据 访问 字段 | 更新日期: 2023-09-27 18:04:31

    <asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False" 
        DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
        <Columns>
            <asp:BoundField DataField="Field1" HeaderText="Field1" 
                SortExpression="Field1" />
            <asp:BoundField DataField="Field2" HeaderText="Field2" 
                SortExpression="Field2" />
            <asp:TemplateField HeaderText="TemplateField1">
                <ItemTemplate>
                    <asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
                </ItemTemplate> 
            </asp:TemplateField>
          <asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                       <asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
                    <asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />    
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

protected void btnComplete_Click(object sender, EventArgs e) 
{
    String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
   //I want to be able to access the row data do some computation and then be able to insert it into the database 
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition. 
}

另外,如果你能让我知道一个更好的方法,也许使用命令字段,如果有一种方法来切换它的可见性,那将是伟大的。我也不介意使用LinkButton。

从模板字段访问GridView数据

你可以这样做:

protected void btnComplete_Click(object sender, EventArgs e)    
{  
     Button btn = (Button)sender;
     GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
     //Alternatively you could use NamingContainer
     //GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
     Label lblComments = (Label)gvRow.FindControl("lblComments");
     // lblComments.Text ...whatever you wanted to do
}

如何访问gridview行:

protected void btnComplete_Click(object sender, EventArgs e)    
{  
     foreach (GridViewRow row in gvGrid.Rows)
      {
            Label lblComments = row.FindControl("lblComments") as Label;
            ....//you can do rest of the templatefiled....
      }
}