我有一个GridView
,每行有一个ImageButton
。我希望在单击按钮时从模板字段中获取值。我在SelectedIndex
中使用了button_click
。
但是SelectedIndex
总是-1。
我试过的代码如下。
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
int i = GridView1.SelectedIndex;
Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
Session["course"] = t.Text;
Response.Redirect("registration.aspx");
}
答案 0 :(得分:1)
答案 1 :(得分:0)
你不会在ButtonCLick事件中获得SelectedIndex
所以试试这个
protected void imgbtn_Click(object sender, EventArgs e)
{
try {
// Get the button that raised the event
LinkButton lnkbtn = (LinkButton)sender;
// Get the row that contains this button
GridViewRow gvRow = (GridViewRow)lnkbtn.NamingContainer;
// Get rowindex
int i = gvRow.RowIndex;
Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
Session["course"] = t.Text;
Response.Redirect("registration.aspx");
}
} catch (Exception ex) {
}
}
protected void grdview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
try {
if ((e.CommandName == "ImageButton")) {
// Get RowIndex
int RowIndex = Convert.ToInt32(e.CommandArgument);
// Get Row
GridViewRow gvr = grdPhone.Rows(RowIndex);
}
} catch (Exception ex)
{
}
}
<强> ASPX:强>
在GridView中
你需要像这样设置CommandName和Argument
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:ImageButton ID="imgbtn" runat="server" OnClick="imgbtn_Click" CausesValidation="false" CommandName="ImageButton" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:ImageButton >
</ItemTemplate>
</asp:TemplateField>