简体   繁体   中英

How to clear gridview on new Select (ASP.NET)

I'm trying to create a table depending on the dropdown value I select, but when I make another choice, the tables don't clear themselves and I get a new table next to the previous one as a result.

ASP code is this:

    <div>         
    <div id="div_LH">
        <div id="div_left">
            <asp:Label Text="Fecha desde: " CssClass="cssLabels" runat="server" /><input type="text" id="datepickerFrom" runat="server"/>
        </div>
        <div id="div_right">
            <asp:Label Text="Fecha hasta: " CssClass="cssLabels" runat="server" /><input type="text" id="datepickerTo" runat="server"/>
        </div>
        <br />
        <div id="div_tipoHab">
            <asp:Label Text="Tipo habitación: " CssClass="cssLabels" runat="server" /><asp:DropDownList ID="ddl_tipoHabitaciones" CssClass="cssLabels"  runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddl_tipoHabitaciones_SelectedIndexChanged"></asp:DropDownList>
        </div>  
    </div>
    <div id="hola" runat="server">
    <asp:GridView CssClass="cssLabels" ID="grid_view_habitaciones" runat="server" BorderColor="#CCCCCC" BorderStyle="Double" GridLines="Horizontal">
    </asp:GridView>

</div>

Code behind:

    Sistema sistema = Sistema.Instancia;

    protected void ddl_tipoHabitaciones_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddl_tipoHabitaciones.SelectedItem != null && datepickerFrom.Value != "" && datepickerTo.Value != "")
        {
            string[] fechaDesdeArray = datepickerFrom.Value.Split('/');
            string[] fechaHastaArray = datepickerTo.Value.Split('/');
            string diaDesdeTexto = fechaDesdeArray[0];
            string diaHastaTexto = fechaHastaArray[0];
            int diaDesde;
            int diaHasta;
            string mesDesdeTexto = fechaDesdeArray[1];
            string mesHastaTexto = fechaHastaArray[1];
            int mesDesde;
            int mesHasta;
            string anioDesdeTexto = fechaDesdeArray[2];
            string anioHastaTexto = fechaHastaArray[2];
            int anioDesde;
            int anioHasta;
            if (int.TryParse(diaDesdeTexto, out diaDesde) && int.TryParse(mesDesdeTexto, out mesDesde)
                    && int.TryParse(anioDesdeTexto, out anioDesde) && int.TryParse(anioHastaTexto, out anioHasta)
                    && int.TryParse(mesHastaTexto, out mesHasta) && int.TryParse(diaHastaTexto, out diaHasta))
            {
                DateTime fechaDesde = new DateTime(anioDesde, mesDesde, diaDesde);
                DateTime fechaHasta = new DateTime(anioHasta, mesHasta, diaHasta);
                List<Habitacion> habitaciones = sistema.ObtenerHabitacionesDisponiblesXTipo(fechaDesde, fechaHasta, ddl_tipoHabitaciones.SelectedItem.Value);
                hola.Visible = true;
                int cantidadPasajeros;
                List<ArrayList> diccHabitaciones = sistema.obtenerHabitacionesIguales(habitaciones, out cantidadPasajeros);
                grid_view_habitaciones.AutoGenerateColumns = false;

                string nuHabit = "Numero de Habitaciones disponibles";
                string tieneJac = "Jacuzzi";
                string esExt = "Exterior";
                string cantCamSimples = "Cantidad de camas Simples";
                string cantCamDobles = "Cantidad de camas Dobles";
                string precio = "Precio (U$S)";

                DataTable table = new DataTable();
                DataColumn columnNumHabit = new DataColumn(nuHabit, typeof(System.Int32));
                table.Columns.Add(columnNumHabit);
                DataColumn columnTieneJacuzzi = new DataColumn(tieneJac, typeof(System.Boolean));
                table.Columns.Add(columnTieneJacuzzi);
                DataColumn columnEsExterior = new DataColumn(esExt, typeof(System.Boolean));
                table.Columns.Add(columnEsExterior);
                DataColumn columnCantCamasSingles = new DataColumn(cantCamSimples, typeof(System.Int32));
                table.Columns.Add(columnCantCamasSingles);
                DataColumn columnCantCamasDobles = new DataColumn(cantCamDobles, typeof(System.Int32));
                table.Columns.Add(columnCantCamasDobles);
                DataColumn columnPrecio = new DataColumn(precio, typeof(System.Decimal));
                table.Columns.Add(columnPrecio);

                for (var i = 0; i < diccHabitaciones.Count ; i++)
                {
                    DataRow row = table.NewRow();
                    row[nuHabit] = diccHabitaciones[i][0];
                    Habitacion habitacion = (Habitacion)diccHabitaciones[i][1];
                    row[tieneJac] = habitacion.TieneJacuzzi;
                    row[esExt] = habitacion.EsExterior;
                    row[cantCamSimples] = habitacion.CantCamasSingles;
                    row[cantCamDobles] = habitacion.CantCamasDobles;
                    row[precio] = habitacion.Precio.MontoDolares;
                    table.Rows.Add(row);
                }

                foreach (DataColumn dc in table.Columns)
                {
                    if (dc.DataType != typeof(System.Boolean))
                    { 
                        BoundField boundfield = new BoundField();
                        boundfield.DataField = dc.ColumnName;
                        boundfield.HeaderText = dc.ColumnName;
                        boundfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                        boundfield.ControlStyle.Width = Unit.Pixel(40);
                        grid_view_habitaciones.Columns.Add(boundfield);
                    } else
                    {
                        CheckBoxField checkbox = new CheckBoxField();
                        checkbox.DataField = dc.ColumnName;
                        checkbox.HeaderText = dc.ColumnName;
                        checkbox.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                        grid_view_habitaciones.Columns.Add(checkbox);
                    }
                }


                grid_view_habitaciones.DataSource = table;
                grid_view_habitaciones.DataBind();

            }
        }
    }

Thanks so much. I've been looking for other answers but all of them talk about using dataGridView1.DataSource = null; or dataGridView1.Rows.Clear(); and I don't think that's the issue here or, at least, I wouldn't know where to add it.

You may look around Page.IsPostBack . If the page is requested the first time your GridView gets bound to its DataSource and the datas are rendered on the web page. Since your DropDownList has it's AutoPostBack property set to true, the moment you click on it on a different selection it Posts Back the page to the server

But by default your GridView has it's ViewState property enabled, so ASP .Net will enforce a mechanism that allows it to keep it's datas between a round trip from the server to the client so as to be able to render it event though HTTP is normally stateless. It's a default way to make it looks statefull. Therefore your new datas will be added to the existing one and you will see as a new table next to the former one.

So you should normally have a test at the beginning of your code similar to this

protected void ddl_tipoHabitaciones_SelectedIndexChanged(object sender, EventArgs e)
{
    if (Page.IsPostBack()) {
        // clear the GridView rows here

    }

     // continue with the processing code
    .....
}

The problem is because every time that the method is called it is creating another set of columns. To avoid that problem you could save the DataColumnCollection into a Session variable, and then check if that variable is not null.

    if (Session["dataColumns"] == null)
    { 
       foreach (DataColumn dc in table.Columns)
       {
            if (dc.DataType != typeof(System.Boolean))
            { 
                BoundField boundfield = new BoundField();
                boundfield.DataField = dc.ColumnName;
                boundfield.HeaderText = dc.ColumnName;
                boundfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                grid_view_habitaciones.Columns.Add(boundfield);
             } else
             {
                 CheckBoxField checkbox = new CheckBoxField();
                 checkbox.DataField = dc.ColumnName;
                 checkbox.HeaderText = dc.ColumnName;
                 checkbox.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                 grid_view_habitaciones.Columns.Add(checkbox);
             }
        }
        Session["dataColumns"] = table.Columns;
    }

Then you need to clean the Session variable before leave the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM