Mostrar y esconder el contenido de un grid del lado del servidor (.Net) y del lado del cliente (jQuery)

GridView es potente control de ASP.NET el cual puede incluir otros controles dentro de él. Incluso podemos tener un GridView dentro de otro GridView. En este artículo veremos cómo acceder a los controles y eventos de dentro del GridView.

En muchas situaciones, necesitamos hacer uso de los controles anidados. ¿Y cual es mejor control de ASP.NET para ello? Exacto, GridView. Mucha gente no sabe cómo gestionar los controles que están dentro de GridView. Es por eso que me animé a escribir un artículo sobre ello, para que todo el mundo vea que no es una tarea tan dificil y que se puede realizar de varias maneras.

El modo vista del GridView muestra una lista de elementos que enlazan los campos de datos a las columnas y muestra un encabezado en cada columna para identificar el campo. El estilo predeterminado del GridView implementa los botones como encabezados de columna. Mediante el uso de estos botones para los encabezados de columnas, puedes implementar importantes funciones para que el usuario interactúe. Por ejemplo, que los usuarios pueden hacer clic en el encabezado de columna para ordenar los datos del GridView según el contenido de una columna específica.

Las columnas del GridView se representan mediante objetos GridViewColumn, que pueden redimensionar automáticamente su contenido. Opcionalmente, puedes establecer explícitamente una GridViewColumn con un ancho específico. Puedes cambiar el tamaño de las columnas arrastrando el gripper entre los encabezados de las columnas. También puedes añadir, quitar, reemplazar y reordenar columnas dinámicamente porque esta funcionalidad está integrada en GridView. Sin embargo, GridView no puede actualizar directamente los datos que muestra.

Ahora os explicaré cómo acceder a los controles y eventos usando RowCommand y jQuery

Uso de RowCommand

El evento RowCommand se produce cuando se hace clic en un botón del control GridView. Esto te proporciona un método de manejo de eventos que realiza una rutina personalizada cuando se produce este evento. Esto significa que al hacer clic en el botón dentro del GridView puedes realizar operaciones personalizadas. Utilizaremos CommandName para darle un nombre único y así identificar el evento.

En el siguiente ejemplo, agrego filas en GridView utilizando DataTable en el evento PageLoad.

GridView_CodeBehind.aspx.cs

protected void Page_Load(object sender, EventArgs e)//page load event
{
    if (!this.IsPostBack)
    {
        load_gridviewrecords();// calling function to add rows into GridView 
    }
}
private void load_gridviewrecords() // adding 3 rows
{
    DataTable dt = new DataTable();
    dt.Columns.Add("jobid");
    dt.Columns.Add("jobtitle");
    dt.Columns.Add("positions");
    dt.Columns.Add("Description");
    DataRow dr1 = dt.NewRow();
    dr1["jobid"] = "JOB122";
    dr1["jobtitle"] = "Software Engineer";
    dr1["positions"] = "10";
    dr1["Description"] = "This job not direct. You have to apply through online. " + 
      "Qualification required BE (Computer Science), M.Tech(Computer Science), " + 
      "MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr1);
    DataRow dr2 = dt.NewRow();
    dr2["jobid"] = "JOB123";
    dr2["jobtitle"] = "Associate System Engineer";
    dr2["positions"] = "100";
    dr2["Description"] = "This job not direct. You have to apply through online. " + 
      "Basic knowledge of web development. Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr2);
    DataRow dr3 = dt.NewRow();
    dr3["jobid"] = "JOB124";
    dr3["jobtitle"] = "Web designer";
    dr3["positions"] = "5";
    dr3["Description"] = "This job not direct. You have to apply through online. " + 
      "Required skills css, Jquery, Html, Photoshop. Qualification required BE " + 
      "(Computer Science), M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr3);
    dt.AcceptChanges();
    GridView1.DataSource = dt;
    GridView1.DataBind();
    
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)// on imagebutton click
{
    if (e.CommandName == "showhide")
    {
        int index = int.Parse(e.CommandArgument.ToString());
        GridViewRow gr = GridView1.Rows[index];
        ImageButton imgbtn = (ImageButton)gr.FindControl("ImageButton1");
        Panel pnl = (Panel)gr.FindControl("pnlOrders");
        if (pnl.Visible == false)
        {
            imgbtn.ImageUrl = "minus.jpg";
            pnl.Visible = true;
        }
        else
        {
            imgbtn.ImageUrl = "plus.jpg";
            pnl.Visible = false;
        }
    }
}

GridView_CodeBehind.aspx

<style type="text/css">
        body{font-family:Calibri;}
    .jobid{float:left; width:100px; height:auto;}
    .jobtitle{float:left; width:300px; height:auto;}
    .noofpositions{float:left; width:100px; height:auto;}
    .div_parent{float:left; width:100%; height:auto;}
    .panel_description{float:left; width:100%; height:auto;}
    </style>

<asp:GridView ID="GridView1" runat="server" 

            ShowHeader="false" ShowFooter="false"

            AutoGenerateColumns="false" GridLines="None" Border="1" 

            onrowcommand="GridView1_RowCommand" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <div style="width:500px; height:auto;">
                    <div class="jobid">
                        <asp:Label ID="Label1" runat="server" 

                              Text='<%# Eval("jobid") %>'></asp:Label>
                    </div>
                    <div class="jobtitle">
                        <asp:Label ID="Label2" runat="server" 

                              Text='<%# Eval("jobtitle") %>'></asp:Label>
                    </div>
                    <div class="noofpositions">
                        <asp:Label ID="Label3" runat="server" 

                           Text='<%# Eval("positions") %>'></asp:Label>
                    </div>
                    <div style="clear:both; height:auto; border-top:solid 1px #e2e2e2;"></div>
                        <div class="div_parent">
                            <asp:ImageButton ID="ImageButton1" CommandName="showhide" 

                              CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 

                              style="cursor: pointer" ImageUrl="plus.jpg" 

                              width="40" height="40" 

                              title="Description" runat="server" />
                        </div>
                        <asp:Panel ID="pnlOrders" class="panel_description" 

                                  runat="server" Visible="false">
                            <asp:Label ID="lblMsg" runat="server" 

                              Text='<%# Eval("description") %>'></asp:Label>
                        </asp:Panel>
               </div>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Inicialmente estoy haciendo el panel que contiene la descripción y estableciendo la visibility a false. El OnClick del botón hace que la visibility del panel vuelva a true basándonos en el RowIndex también cambiando la imagen de ImageButton a minus.jpg.

Haciendo lo mismo con jQuery

GridView_JQuery.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        load_gridviewrecords();
    }
}
private void load_gridviewrecords()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("jobid");
    dt.Columns.Add("jobtitle");
    dt.Columns.Add("positions");
    dt.Columns.Add("Description");
    DataRow dr1 = dt.NewRow();
    dr1["jobid"] = "JOB122";
    dr1["jobtitle"] = "Software Engineer";
    dr1["positions"] = "10";
    dr1["Description"] = "This job not direct. You have to apply through online. " + 
      "Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr1);
    DataRow dr2 = dt.NewRow();
    dr2["jobid"] = "JOB123";
    dr2["jobtitle"] = "Associate System Engineer";
    dr2["positions"] = "100";
    dr2["Description"] = "This job not direct. You have to apply through online. " + 
      "Basic knowledge of web development. Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr2);
    DataRow dr3 = dt.NewRow();
    dr3["jobid"] = "JOB124";
    dr3["jobtitle"] = "Web designer";
    dr3["positions"] = "5";
    dr3["Description"] = "This job not direct. You have to apply through " + 
      "online. Required skills css, Jquery, Html, Photoshop. Qualification required BE " + 
      "(Computer Science), M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr3);
    dt.AcceptChanges();
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

GridView_JQuery.aspx

<style type="text/css">
        body{font-family:Calibri;}
    .jobid{float:left; width:100px; height:auto;}
    .jobtitle{float:left; width:300px; height:auto;}
    .noofpositions{float:left; width:100px; height:auto;}
    .div_parent{float:left; width:100%; height:auto;}
    .panel_description{float:left; width:100%; height:auto;}
    </style>
 
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
    $('.div_parent img').each(function()
    {
        var flag_click=0;
        $(this).click(function()
        {
            if(flag_click===0)
            {
                $(this).attr("src","minus.jpg");
                $(this).parent(".div_parent").next(".panel_description").show();
                flag_click++;
            }
            else
            {
                $(this).attr("src","plus.jpg");
                $(this).parent(".div_parent").next(".panel_description").hide();
                flag_click=0;
            }
        });
    });
});
</script>
<asp:GridView ID="GridView1" runat="server" 

            ShowHeader="false" ShowFooter="false"

            AutoGenerateColumns="false" GridLines="None" Border="1">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <div style="width:500px; height:auto;">
                    <div class="jobid">
                        <asp:Label ID="Label1" runat="server" 

                          Text='<%# Eval("jobid") %>'></asp:Label>
                    </div>
                    <div class="jobtitle">
                        <asp:Label ID="Label2" runat="server" 

                          Text='<%# Eval("jobtitle") %>'></asp:Label>
                    </div>
                    <div class="noofpositions">
                        <asp:Label ID="Label3" runat="server" 

                           Text='<%# Eval("positions") %>'></asp:Label>
                    </div>
                    <div style="clear:both; height:auto; border-top:solid 1px #e2e2e2;"></div>
                        <div class="div_parent">
                        <img alt="" style="cursor: pointer"

                           src="plus.jpg" width="40" height="40" 

                           title="Description" /></div>
                        <asp:Panel ID="pnlOrders" class="panel_description" 

                                    runat="server" Style="display:none;">
                            <asp:Label ID="lblMsg" runat="server" 

                               Text='<%# Eval("description") %>'></asp:Label>
                        </asp:Panel>
                   </div>
                        
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

En este ejemplo, hemos utilizado la función de jQuery parent() para encontrar el control padre y next() para encontrar controles inmediatos. Después de encontrar el control, utilizando las funciones show() y hide() podemos hacer que el control del panel se muestre y se oculte, respectivamente.

Fuente: vinodkumarnie

Guardar

Guardar

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP