Grid control buttons
I have a gridview control that displays data returned from a DB. Datakey gridview property bound to db id column
Each entry in the GV had 2 buttons and one checkbox. When one of these controls is clicked, I want to get the row that the button was clicked on and take an action based on which control was clicked.
I was hoping I could use an event row_command
to capture which control was clicked, but that didn't do the trick unless I missed something.
0
source to share
4 answers
Code for:
protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("RowSelected"))
{
GridViewRow row = (((e.CommandSource) as Button).NamingContainer) as GridViewRow;
Label label = row.FindControl("lblFirstName") as Label;
Response.Write(label.Text);
}
}
And here's the ASPX View:
<asp:GridView AutoGenerateColumns="false" ID="gvCustomers" runat="server" OnRowCommand="gvCustomers_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text ='<%# Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Select" ID="btn1" runat="server" CommandArgument ='<%# Eval("FirstName") %>' CommandName="RowSelected" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
0
source to share
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"OnRowCommand="gvProduct_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="EditCommand" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProjectNo" HeaderText="ProjectNo" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Shift" HeaderText="شیفت" />
</Columns>
</asp:GridView>
and this code:
protected void gvProduct_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditCommand")
{
GridViewRow Row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int productID = Convert.ToInt32(gvProduct.DataKeys[Row.RowIndex].Value);
EditFunction(productID);
}
}
EditFunction
is the function you set for the selected row and I removed it here.
Do you need something like this?
0
source to share