I need to click a button that is inside a gridview from the codebehind. I think the best approach will be to create a javascript function in codebehind, something like the second solution i tried below. I will appreciate any help
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accepted")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
//find button
Button btnEsc = (Button)row.FindControl("btnEsc");
//here I would like to simulate a click on this button, so far no luck
btnEsc.Click(); // this is wrong
}
}
I also try this but it doesn't find the button: I dont know how to find the button inside the gridview
System.Text.StringBuilder sbScript = new System.Text.StringBuilder("");
sbScript.Append("document.getElementById('btnEsc').click();");
ScriptManager.RegisterStartupScript(this, GetType(), "ClientScript", sbScript.ToString(), true);
Code behind:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btn.Text = "Refreshed";
if (Request.Params["btnPressed"] != null && Request.Params["btnPressed"] == "true")
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", string.Format("$('#{0}').click()", btn.ClientID), true);
}
}
protected void btn_Click(object sender, EventArgs e)
{
btn.Text = "Not Refreshed";
lbl.Text = "Not Refreshed";
System.Threading.Thread.Sleep(1000);
////to refresh the page
Page.Response.Redirect(HttpContext.Current.Request.Url.ToString()+"?btnPressed=true", true);
}
}
Load jquery in aspx page:
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btn" OnClick="btn_Click" PostBackUrl="/WebForm1.aspx" />
<asp:Label runat="server" ID="lbl"> </asp:Label>
</div>
</form>
</body>
You should really learn jquery, its a great tool. g/l.