How to Add jquery .trigger() in codeBehind ASP.net C#

I need to auto-Click on a hidden button after the Gridview is generated, I have:

$("#<%=btnExcel.ClientID%>").trigger("click");

works perfectly but I need to add it Codebehind after the Gridview is generated, I tried adding a function and then call it in the OnRowdatabound event:

//I tried creating a function
<script type="text/javascript">
    function Excel() {
        $("#<%=btnExcel.ClientID%>").trigger("click");
    }
</script>

All CS code

public partial class ReportesCasos : System.Web.UI.Page
{
    string BaseX = "SELECT DISTINCT Casos.Cliente AS idCliente, Casos.Asignado AS Usuario, Casos.idCaso AS 'N° Caso', Clientes.nombre AS Cliente,Asunto, Estado.Descripcion AS 'Estado Actual', Causa.Descripcion AS Causa_Raiz, Usuarios.Login AS 'Tecnico_Asignado', Zona.Descripcion AS 'Zona', Sector.Sector AS 'Sector', Usuarios.Login AS 'Asignado', CONVERT (nchar, Casos.Reportado, " + funciones.Fecha() + ") AS Reportado, CONVERT (nchar, Casos.Cerrado, " + funciones.Fecha() + ") AS Cerrado, CONVERT (nchar, Casos.Vencimiento, " + funciones.Fecha() + ") AS Vencimiento,fecha, CONVERT(nchar,fecha," + funciones.Fecha() + ") As Fecha2, TipoCaso.Descripcion AS TipoCaso, Prioridad.Descripcion AS Prioridad, Casos.Horas AS HorasTrabajadas, Casos.Atendidos AS EquiposAtendidos, Casos.Contrato AS BajoContrato, Casos.Valoracion AS Evaluacion, Casos.Facturado AS facturado, Casos.Factura AS 'N° Factura', Casos.Contacto AS ContactoCliente, Casos.Diagnostico AS Diagnostico, Casos.Solucion AS Solucion FROM Casos INNER JOIN TipoCaso ON Casos.TipoCaso = TipoCaso.idTipo INNER JOIN Prioridad ON Casos.Prioridad = Prioridad.idPrioridad INNER JOIN Estado ON Casos.Estado = Estado.idEstado INNER JOIN Usuarios ON Casos.Asignado = Usuarios.idUsuario INNER JOIN clientes ON idCliente = Casos.Cliente INNER JOIN (SELECT Caso,MAX(Fecha)AS Fecha FROM HistorialEstado";
    string BaseX1 = " GROUP BY Caso) AS HistorialEstado ON Caso = idCaso INNER JOIN Zona ON Casos.Zona = Zona.idZona INNER JOIN Sector ON Casos.Sector = Sector.idSector INNER JOIN Causa ON Casos.Causa = Causa.idCausa WHERE tipocaso <> 5 AND ";
    string ColaX2 = " ORDER BY idCaso";
    string ClienteX = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["Usuario"] == null || Session["Sesion"] == null || !funciones.ChequearUsuario(Request.Cookies["Usuario"]["sesion"], Session["Sesion"].ToString()) || Session["Nivel"].ToString() == "3")
        {
            Response.Redirect("index.aspx");
        }
        Session["Titulo"] = "REPORTE EN GENERAL";
        Session["Error"] = "";
        if (Session["Cliente"].ToString() != "")
        {
            Cliente = " AND Casos.Cliente = '" + Session["Cliente"].ToString() + "'";
        }
        else
        {
            Cliente = "";
        }

    }
    protected void dlPeriodo_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (dlPeriodo.SelectedIndex != 6)
        {
            lblDesde.Visible = false;
            lblHasta.Visible = false;
            tbDesde.Visible = false;
            tbHasta.Visible = false;
        }
        else
        {
            lblDesde.Visible = true;
            lblHasta.Visible = true;
            tbDesde.Visible = true;
            tbHasta.Visible = true;
        }
    }
    protected void btnVer2_Click(object sender, ImageClickEventArgs e)
    {
        
        if (dlPeriodo.SelectedIndex != 6)
        {
            SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
            Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;
            
        }
        else
        {
            DateTime Fecha;
            if (DateTime.TryParse(tbDesde.Text, out Fecha))
            {
                if (DateTime.TryParse(tbHasta.Text, out Fecha))
                {
                    SqlDataSourceBusqueda2.SelectCommand = BaseX + BaseX1 + " Fecha >= CONVERT(DateTime,'" + DateTime.Now.AddDays(-Int32.Parse(dlPeriodo.SelectedValue)).ToShortDateString() + "'," + funciones.Fecha() + ") AND Fecha <= CONVERT(DateTime,'" + DateTime.Now.AddDays(1).ToShortDateString() + "'," + funciones.Fecha() + ")" + ClienteX;
                    Session["Sql"] = SqlDataSourceBusqueda2.SelectCommand;

                }
                else
                {
                    string Formato = "";
                    if (funciones.Fecha() == "101")
                    {
                        Formato = " mm/dd/aaaa";
                    }
                    else
                    {
                        Formato = " dd/mm/aaaa";
                    }
                    Session["Error"] = "La fecha debe ser de la forma" + Formato;
                }
            }
            else
            {
                string Formato = "";
                if (funciones.Fecha() == "101")
                {
                    Formato = " mm/dd/aaaa";
                }
                else
                {
                    Formato = " dd/mm/aaaa";
                }
                Session["Error"] = "La fecha debe ser de la forma" + Formato;
            }

        }
            
    }
protected void grdCartelera2_PageIndexChanged(object sender, EventArgs e)
    {
        SqlDataSourceBusqueda2.SelectCommand = Session["Sql"].ToString();
    }
protected void grdCartelera2_Sorted(object sender, EventArgs e)
    {
        SqlDataSourceBusqueda2.SelectCommand = Session["sql"].ToString();  
    }
private void ExportGridToExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Redex_ReporteCasos"));
        Response.Charset = "";
        StringWriter stringwriter = new StringWriter();
        HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
        GridView2.RenderControl(htmlwriter);
        Response.Write(stringwriter.ToString());
        Response.End();
        ExportGridToExcel();

    }      
    protected void btnexportExcel_Click(object sender, ImageClickEventArgs e)
     {
        ExportGridToExcel(); 
     }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (funciones.Anexos(((System.Web.UI.WebControls.HyperLink)(e.Row.Cells[1].Controls[0])).Text))
            {
                Image Imagen = new Image();
                Imagen.ImageUrl = "~/Imagenes/Iconos/anexo.png";
                e.Row.Cells[0].Text = "Si";
                
            }
            else
            {
                e.Row.Cells[0].Text = "No";
                
            }
            
            string BajoContrato = e.Row.Cells[15].Text.ToString();
            if (BajoContrato == "False")
            {
                e.Row.Cells[15].Text = "No";
            }
            else
            {
                e.Row.Cells[15].Text = "Si";
            }
            btnexportExcel_Click(null, null);
        }
        
    }
    public override void VerifyRenderingInServerForm(Control control) {} 
}

ASPX

<table style="width: 770px; height: 492px">
            <tr>
                <td align="center" style="height: 7%;" valign="middle">
                    <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="En el periodo" Font-Size="Small"></asp:Label></td>
                <td align="center" style="height: 7%;" valign="middle">
                    <asp:DropDownList ID="dlPeriodo" runat="server" BackColor="AliceBlue"
                        EnableTheming="True" Font-Bold="True" Font-Names="Century Gothic" ForeColor="#00C000"
                        OnSelectedIndexChanged="dlPeriodo_SelectedIndexChanged" Width="192px" Font-Size="Small" AutoPostBack="True">
                        <asp:ListItem Value="0">Hoy</asp:ListItem>
                        <asp:ListItem Value="1">1 Dia</asp:ListItem>
                        <asp:ListItem Value="5">5 Dias</asp:ListItem>
                        <asp:ListItem Value="7">7 Dias</asp:ListItem>
                        <asp:ListItem Value="15">15 Dias</asp:ListItem>
                        <asp:ListItem Value="30">30 Dias</asp:ListItem>
                        <asp:ListItem Value="6">Especifico</asp:ListItem>
                    </asp:DropDownList></td>
                <td align="center" style="height: 7%; text-align: right;" valign="middle">
                    <asp:ImageButton ID="btnVer" runat="server" Height="24px" ImageUrl="~/Imagenes/Iconos/buscar.png"
                        OnClick="btnVer_Click" Width="22px" /></td>
                <td align="left" colspan="1" valign="middle" class="style1">
                    &nbsp;<asp:ImageButton ID="btnVer0" runat="server" 
                        Height="20px" ImageUrl="~/Imagenes/Iconos/excel.png"
                        OnClick="btnVer2_Click" Width="26px" /> 
                    <asp:ImageButton ID="btnExcel" style="visibility: hidden; display: none;" runat="server" ImageUrl="~/Imagenes/Iconos/excel.png"
                        OnClick="btnexportExcel_Click" Width="20px" Height="21px"/>
                    </td>
                <td align="center" colspan="2" style="height: 7%" valign="middle">
                    &nbsp;</td>
            </tr>
            <tr>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:Label ID="lblDesde" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="Desde" Visible="False" Font-Size="Small"></asp:Label></td>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:TextBox ID="tbDesde" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px" 
                        Font-Size="Small"></asp:TextBox></td>
                <td align="center" style="height: 8%;" valign="middle">
                    <asp:Label ID="lblHasta" runat="server" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" Text="Hasta" Visible="False" Font-Size="Small"></asp:Label></td>
                <td align="left" valign="middle" class="style2">
                    <asp:TextBox ID="tbHasta" runat="server" BackColor="AliceBlue" Font-Bold="True" Font-Names="Century Gothic"
                        ForeColor="#00C000" MaxLength="50" Visible="False" Width="192px" 
                        Font-Size="Small"></asp:TextBox></td>
                <td align="center" style="height: 8%" valign="middle" colspan="2">
                    &nbsp;</td>
            </tr>
            <tr>
                <td align="left" colspan="6" style="height: 105%" valign="top">
                <%if(Session["Nivel"].ToString() != "4"){ %>
                    <asp:GridView ID="GridView2" runat="server" AllowPaging="False"
                        CellPadding="2" DataSourceID="SqlDataSourceBusqueda2" Font-Names="Century Gothic"
                        ForeColor="#333333" GridLines="None" PageSize="50" Width="769px" 
                        AutoGenerateColumns="False" Font-Size="Small" 
                        OnPageIndexChanged="grdCartelera2_PageIndexChanged" 
                        OnSorted="grdCartelera2_Sorted"  OnRowDataBound="GridView2_RowDataBound">
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <Columns>
                            <asp:ImageField HeaderText="Anexos">
                            </asp:ImageField>
                            <asp:HyperLinkField DataNavigateUrlFields="N° Caso" DataNavigateUrlFormatString="Casos.aspx?idCaso={0}"
                                DataTextField="N° Caso" HeaderText="Caso"
                                SortExpression="N° Caso" />
                            <asp:BoundField DataField="Cliente" HeaderText="Cliente" SortExpression="Cliente" />
                            <asp:BoundField DataField="ContactoCliente" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Contacto Cliente" SortExpression="ContactoCliente" />
                            <asp:BoundField DataField="TipoCaso" HeaderText="Tipo Caso" SortExpression="TipoCaso" />
                            <asp:BoundField DataField="Asunto" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Asunto" SortExpression="Asunto" />
                            <asp:BoundField DataField="Asignado" HeaderText="Tecnico" SortExpression="Asignado" />
                            <asp:BoundField DataField="Causa_Raiz" HeaderText="Causa Raiz" SortExpression="Causa_Raiz" />
                            <asp:BoundField DataField="Zona" HeaderText="Zona" SortExpression="Zona" />
                            <asp:BoundField DataField="Sector" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Sector" SortExpression="Sector" />
                            <asp:BoundField DataField="Estado Actual" HeaderText="Estado" SortExpression="Estado Actual" />
                            <asp:BoundField DataField="Prioridad" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Prioridad" SortExpression="Prioridad" />
                            <asp:BoundField DataField="HorasTrabajadas" HeaderText="Horas Trabajadas" SortExpression="HorasTrabajadas" />
                            <asp:BoundField DataField="Evaluacion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Evaluacion" SortExpression="Evaluacion" />
                            <asp:BoundField DataField="EquiposAtendidos" HeaderText="Equipos Atendidos" SortExpression="EquiposAtendidos" />
                            <asp:BoundField DataField="BajoContrato" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Bajo Contrato" SortExpression="BajoContrato" />
                            <asp:BoundField DataField="N° Factura" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="N°Factura" SortExpression="N° Factura" />
                            <asp:BoundField DataField="Diagnostico" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Diagnostico" SortExpression="Diagnostico" />
                            <asp:BoundField DataField="Solucion" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Solucion" SortExpression="Solucion" />
                            <asp:BoundField DataField="Reportado" HeaderText="Reportado" SortExpression="Reportado" />
                            <asp:BoundField DataField="Cerrado" HeaderStyle-CssClass="hiddencol" ItemStyle-CssClass="hiddencol" HeaderText="Cerrado" SortExpression="Cerrado" />
                            <asp:BoundField DataField="Vencimiento" HeaderText="Vencimiento" SortExpression="Vencimiento" />
                        </Columns>
                        <RowStyle BackColor="#EFF3FB" />
                        <EditRowStyle BackColor="#2461BF" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                    <%}%>
<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" ConnectionString="<%$ ConnectionStrings:conexion %>"
                        ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"></asp:SqlDataSource>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are several solutions to this but it would take you to try out multiple of them so you can analyze which one suits your needs.

Solution 1 If you intend to execute a server side event, you can simply call that method from your code behind instead of faking the click. Call your event method like this in the code behind.

btnExcel_Clicked(null, null);

You can consume it like this:

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    btnExcel_Clicked(null, null); //  I assume your btnExcel button is linked to this event.
}

Solution 2 If it is required that you must only use JavaScript/Jquery this can be helpful.

var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger", 
    "$("#"+ myButtonID +"").trigger("click");", true);

Solution 3 Solution 2, with javascript event.

var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger",
    "document.getElementById(" + myButtonID + ").onclick();", true);

I do not think it is a good Idea to call it on a RowDataBound event, as it will trigger it many times not only when the grid view is loaded. So, you must call it after you have called GridView2.DataBind() method, not inside of a RowDataBound event.


Solution 4 This is a pure, page flow based solution. The trick is to execute the javascript from the javascript by using a CodeBehind flag. Here it is how you would do that:

First Declare a property in the CodeBehind.

public bool ShouldTriggerClickEvent { get; set; }

Then, in your Page_Load event, assign flase as value to this property, and make it true when your RowDataBound event is completely triggered. See:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostback)
    {
        ShouldTriggerClickEvent = false;
    }
}

Now, in your RowDataBound event make it true.

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    ShouldTriggerClickEvent = true;
}

And now, when the page load completes, you need to check this flag on the client side, and execute the code if the flag is true. Like below:

<script>
    $(document).ready(function(){
        function shouldTriggerClickEvent(){
            return '<%= ShouldTriggerClickEvent %>' == 'True';
        }
        if (shouldTriggerClickEvent()){
            $("#<%=btnExcel.ClientID%>").trigger("click");
        }
    });
</script>

I have mentioned multiple solution that I could so far memorize, you can see which one works for you fine.


UPDATE

As you are asking where to call the method, I would suggest calling the method right after you bind your DataSource.

// After this line
GridView2.DataBind(); //  so each time the data is populated in it, this will method will be called
btnExcel_Clicked(null, null);

You can also check if your DataSource has items in it, only then you might want to call it, as you asked when the GridView is loaded, which I assume means, will only load after it has rows in it.

// Lets assume you have a DataTable object that is the DataSource of the GridView
var dataTable = GetDataTable(); // Some method that will fetch the rows

GridView2.DataSource = dataTable;
GridView2.DataBind(); //  so each time the data is populated in it, this will method will be called
if (dataTable != null && dataTable.Rows.Count > 0)
{
    btnExcel_Clicked(null, null);
}

UPDATE 2

Okay, so you want to call execute the Event after the Data has been bound to your GridView and you are using SqlDataSource to bind the GridView. Here is my suggestion on modification.

Replace your SqlDataSource to include OnSelected event.

<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" 
     ConnectionString="<%$ ConnectionStrings:conexion %>"
     ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"
     OnSelected="SqlDataSourceBusqueda2_Selected">
</asp:SqlDataSource>

And Add this method/event inside of your CodeBehind

protected void SqlDataSourceBusqueda2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    // Your Code goes here.
    btnExcel_Clicked(null, null);
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x