<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。
答案 0 :(得分:3)
你可以这样做:
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
}
答案 1 :(得分:1)
以下是访问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....
}
}