C# 帮助Kamran@Hlvr当然,如果您在解决方案中遇到任何问题,请告诉我。选项1非常有效,现在不需要JS,我只是不知道将其放置在何处以捕获所有数据。你是对的RowDataBound只带来没有数据或一些数据,这取决于我应该把它放在哪里?我正在用所有CS代码更

C# 帮助Kamran@Hlvr当然,如果您在解决方案中遇到任何问题,请告诉我。选项1非常有效,现在不需要JS,我只是不知道将其放置在何处以捕获所有数据。你是对的RowDataBound只带来没有数据或一些数据,这取决于我应该把它放在哪里?我正在用所有CS代码更,c#,jquery,asp.net,aspxgridview,C#,Jquery,Asp.net,Aspxgridview,帮助Kamran@Hlvr当然,如果您在解决方案中遇到任何问题,请告诉我。选项1非常有效,现在不需要JS,我只是不知道将其放置在何处以捕获所有数据。你是对的RowDataBound只带来没有数据或一些数据,这取决于我应该把它放在哪里?我正在用所有CS代码更新问题。请在绑定gridview后立即进行GridView2.DataBind()或者,比较数据源中是否有项,然后调用该事件。检查更新 $("#<%=btnExcel.ClientID%>").trigger(&


帮助Kamran@Hlvr当然,如果您在解决方案中遇到任何问题,请告诉我。选项1非常有效,现在不需要JS,我只是不知道将其放置在何处以捕获所有数据。你是对的RowDataBound只带来没有数据或一些数据,这取决于我应该把它放在哪里?我正在用所有CS代码更新问题。请在绑定gridview后立即进行
GridView2.DataBind()
或者,比较数据源中是否有项,然后调用该事件。检查更新
$("#<%=btnExcel.ClientID%>").trigger("click");
//I tried creating a function
<script type="text/javascript">
    function Excel() {
        $("#<%=btnExcel.ClientID%>").trigger("click");
    }
</script>
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) {} 
}
<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&#176; Caso" DataNavigateUrlFormatString="Casos.aspx?idCaso={0}"
                                DataTextField="N&#176; Caso" HeaderText="Caso"
                                SortExpression="N&#176; 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>
btnExcel_Clicked(null, null);
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    btnExcel_Clicked(null, null); //  I assume your btnExcel button is linked to this event.
}
var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger", 
    "$("#"+ myButtonID +"").trigger("click");", true);
var myButtonID = btnExcel.ClientID;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Trigger",
    "document.getElementById(" + myButtonID + ").onclick();", true);
public bool ShouldTriggerClickEvent { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostback)
    {
        ShouldTriggerClickEvent = false;
    }
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // ... Your code
    ShouldTriggerClickEvent = true;
}
<script>
    $(document).ready(function(){
        function shouldTriggerClickEvent(){
            return '<%= ShouldTriggerClickEvent %>' == 'True';
        }
        if (shouldTriggerClickEvent()){
            $("#<%=btnExcel.ClientID%>").trigger("click");
        }
    });
</script>
// After this line
GridView2.DataBind(); //  so each time the data is populated in it, this will method will be called
btnExcel_Clicked(null, null);
// 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);
}
<asp:SqlDataSource ID="SqlDataSourceBusqueda2" runat="server" 
     ConnectionString="<%$ ConnectionStrings:conexion %>"
     ProviderName="<%$ ConnectionStrings:conexion.ProviderName %>"
     OnSelected="SqlDataSourceBusqueda2_Selected">
</asp:SqlDataSource>
protected void SqlDataSourceBusqueda2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    // Your Code goes here.
    btnExcel_Clicked(null, null);
}