开发者

Accessing GridView data from a templatefield

开发者 https://www.devze.com 2023-03-25 07:00 出处:网络
<asp:GridView ID=\"gvGrid\" runat=\"server\" AutoGenerateColumns=\"False\" DataSourceID=\"dsDataSource\" AllowPaging=\"True\" PageSize=\"20\" >
    <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 visibl开发者_Go百科e when it meets certain condition. 
}

Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.


You can do it like this:

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
}


here is how you can access to the gridview row:

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....
      }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消