问题
I have Gridview with some records (1 record=1 row).
On every row I added a button to delete this record from my mysql db.
Every row has the same button.
The problem is I need to know in which row the button was clicked? I need this to get a row index to get id of my record which is in that row.
How can I do this in easiest way?
Gridview:
<asp:GridView ID="GridView1" runat="server"
CellPadding="6" EnableModelValidation="True" ForeColor="#333333"
GridLines="None" Caption="TWOJE WIZYTY" Font-Bold="True"
onrowcreated="GridView1_RowCreated" style="text-align: left">
<AlternatingRowStyle BackColor="#AEAEAE" />
<EditRowStyle BackColor="Blue" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#868686" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="Blue" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#C7C7C7" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
</asp:GridView>
The button is being added like that:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
Button b1 = new Button();
b1.Text = "usuń";
b1.OnClientClick = "return potwierdzenie()";
b1.Click+=new EventHandler(b1_Click);
TableCell cel = new TableCell();
cel.Width = Unit.Pixel(180);
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[2].Text = "";
e.Row.Cells.Add(cel);
}
else
{
//HERE IS MY BUTTON ADDED! *********************
cel.Controls.Add(b1);
cel.HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[0].Visible = false;
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
e.Row.Cells.Add(cel);
}
}
回答1:
You can use the NamingContainer property of your button to get the GridViewRow. Then you have all you need to find your other controls (f.e. the control with ID if you use TemplateFields).
protected void button_Delete_click(Object sender, EventArgs e)
{
Button btn = (Button) sender;
GridViewRow row = (GridViewRow) btn.NamingContainer;
// assuming you store the ID in a Hiddenield:
Hiddenield hiddenID = (HiddenField) row.FindControl("HiddenID");
int ID = int.Parse(hiddenID.Value);
// delete the record
}
You can also get the row-index via row.RowIndex.
来源:https://stackoverflow.com/questions/14288168/how-to-get-row-index-according-to-clicked-button-from-asp-net-gridview