vendredi 30 mars 2018

ASP.NET Cannot uncheck checkbox

i have this so popular problem that i really cannot fix. I have not yet found a fix for this even if i searched a lot on the web, so please do not mark this as a duplicate since it is not. here is what i am trying to do: I create a GridView based on a XML file, so i create columns and rows based on it. Each cell has got a checkbox that might be check or not depending on some vaules in the xml. I can make the checkboxes already checked or uncheck but here comes a problem. While if a checkbox is not checked and i click it everything goes well, when it is checked and i want to uncheck it, the checkbox just change the check on it without performing action it should do (and it results that its state did not change). How can i fix this? it is really annoying.

Here is some code, sorry if it is not so readable or well made.

    public partial class AggiungiDisponibilita : System.Web.UI.Page
{
    string nomeProclamatore;
    string id;
    string colonna, colonna_c2, colonna_c3, riga, riga_c2, riga_c3;
    /// <summary>
    /// stringe per l'inserimento delle disponibilita
    /// </summary>
    string data, turno;

    string prog, name;
    string mese_prossimo = Home.mese_prossimo;

    protected void Home_Click(object sender, EventArgs e)
    {
        Response.Redirect("Home.aspx?Aggiorna=Nomi");
    }

    protected void selectAll_Click(object sender, EventArgs e)
    {
        var programma = new XmlDocument();
        programma.Load(Server.MapPath(Resources.DisponibilitaXML));
        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
        foreach (XmlNode giorno in mese)
            foreach (XmlElement turni in giorno)
            {
                turni.InnerText += nome.Text + ",";
            }
        programma.Save(Server.MapPath(Resources.DisponibilitaXML));
        Response.Redirect("AggiungiDisponibilita.aspx?Name=" + nomeProclamatore.Replace(" ", "+"));

    }

    protected void deselectAll_Click(object sender, EventArgs e)
    {
        var programma = new XmlDocument();
        programma.Load(Server.MapPath(Resources.DisponibilitaXML));
        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
        foreach (XmlNode giorno in mese)
            foreach (XmlElement turni in giorno)
            {
                string[] nomi = turni.InnerText.Split(',');
                var numero_volte_nomi = nomi.GroupBy(v => v);
                foreach (var nomep in numero_volte_nomi)
                    if (nomep.Count() >= 1 && nomep.Key.ToString() == nome.Text) //il nome appare più di una volta
                    {
                        //rimuoverlo tutte le volte tranne 1 
                        turni.InnerText = turni.InnerText.Replace(nomep.Key.ToString() + ",", "");
                    }
            }
        programma.Save(Server.MapPath(Resources.DisponibilitaXML));
        Response.Redirect("AggiungiDisponibilita.aspx?Name=" + nomeProclamatore.Replace(" ", "+"));
    }

    protected void Gestione_Click(object sender, EventArgs e)
    {
        Response.Redirect("GestioneFratelli.aspx");

    }

    protected void Modifica_Click(object sender, EventArgs e)
    {
        string nome = "";
        if (Session["UserName"] != null)
            try
            {
                nome = Convert.ToString(Session["UserName"]);
            }
            catch (HttpException ex)
            {
            }
        Response.Redirect("ModificaFratello.aspx?Name=" + nome.Replace(" ", "+"));
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["UserName"] != null)
        {

            if (!Session["UserName"].Equals("JonathanImperato"))
            {
                Gestione.Visible = false;
                Homes.Text = "Logout";
            }
            if (!Session["UserName"].Equals(Request.QueryString["Name"]))
            {
                Response.Redirect("Login.aspx", false);
            }
            prog = Server.MapPath(Resources.DisponibilitaXML);
            Mese.Text = "Disponibilita per il mese di: " + Variables.Mese_Succ(DateTime.Now.Month);
            name = Request.QueryString["Name"];
            id = name;

            nomeProclamatore = name.Replace("+", " ");

            nome.Text = nomeProclamatore;
        }
        else Response.Redirect("Login.aspx", false);

    }

    void loadData()
    {
        // instantiate XmlDocument and load XML from file
        XmlDocument doc = new XmlDocument();
        doc.Load(prog); //Percorso file xml



        DataTable dt = new DataTable();
        dt.Columns.Add("Data");
        foreach (XmlNode xns in doc.DocumentElement)
        {
            if (xns.Name == Variables.Mese_Succ(DateTime.Now.Month)) ///IMPLEMENTARE SELEZIONE AUTOMATICA DEL MESE IMPORTANTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 

                foreach (XmlNode xn in xns)
                {
                    string tagName = xn.Name;
                    dt.Rows.Add(tagName);

                }
        }


        dt.Columns.Add("Mattina Turno 1", typeof(Boolean));
        dt.Columns.Add("Mattina Turno 2", typeof(Boolean));
        dt.Columns.Add("Pomeriggio", typeof(Boolean));



        GridView1.DataSource = dt;
        GridView1.DataBind();

        //nascondo tutti i checkbox i cui turni non esistono una volta che tutti i checkbox sono stati inseriti nella GridView
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                foreach (CheckBox checks in row.Cells[i].Controls)
                {
                    int tooltip_lunghezza = checks.ToolTip.Split(',').Count();
                    if (tooltip_lunghezza != 2)
                    {
                        var programma = new XmlDocument();
                        programma.Load(Server.MapPath(Resources.ProgrammaXML));
                        var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
                        // MOSTRA IN AUTOMATICO SOLO I TURNI CHE OGNI GIORNO HA NEL FILE XML, AUTOMATICITA SENZA CONTROLLO DI OGNI GIORNO, FA TUTTO SULLA BASE DELL'EXML
                        //FUNZIONA ANCHE CON I GIORNI AGGIUNTI SUCCESSIVAMENTE
                        string data2 = row.Cells[0].Text;
                        XmlNode giorno = mese.SelectSingleNode(data2);
                        checks.Visible = false;
                        foreach (XmlNode turni in giorno.ChildNodes)
                        {
                            string nome_turno = turni.Name;
                            if (checks.ToolTip.Contains(turni.Name.Replace("_", " ")) && checks.ToolTip.Contains(data2))
                                checks.Visible = true;
                        }
                    }
                    else checks.Visible = false; //nascondo quelli finti
                }
            }
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            prog = Server.MapPath(Resources.DisponibilitaXML);

            id = Request.QueryString["Name"];

            nomeProclamatore = id.Replace("%20", " ");

            nome.Text = nomeProclamatore;
            nome.Text = mese_prossimo;

            loadData();

        }
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        inserisciDisponibilitaGiaDate(e);

    }

    void inserisciDisponibilitaGiaDate(GridViewRowEventArgs e)
    {
        string test;
        CheckBox chk1 = new CheckBox();
        CheckBox chk2 = new CheckBox();
        CheckBox chk3 = new CheckBox();
        prog = Server.MapPath(Resources.DisponibilitaXML);
        var doc = XElement.Load(prog); //Percorso file xml
        //foreach(GridViewRow row in GridView1.Rows)
        // check if it's not a header and footer
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Variables.data_turno = test = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Data"));
            test = Variables.data_turno;

            Variables.row_index = Convert.ToInt32(e.Row.RowIndex);

            chk1.CausesValidation = false;
            chk1.AutoPostBack = true;
            chk1.Checked = false;

            chk1.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna = GridView1.HeaderRow.Cells[1].Text;
            chk1.ID = colonna + e.Row.RowIndex;
            chk1.ViewStateMode = ViewStateMode.Enabled;
            chk1.ToolTip = Variables.row_index + "," + test + "," + colonna + ",false";


            //se è gia stata data la disponibilita metto il checkbox su cliccato
            if (test.Length > 0 && colonna.Length > 0)
            {
                var saveGame = doc
                //.Element("Anno_"+DateTime.Now.Year.ToString())
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna.Replace(" ", "_"))
                .Single();

                string esiste_gia = saveGame.Value;
                if (esiste_gia.Contains(nomeProclamatore))
                {
                    chk1.Checked = true;
                    chk1.ToolTip = Variables.row_index + "," + test + "," + colonna + ",true";
                }
            }
            //-------------------------------------------- 

            chk2.CausesValidation = false;
            chk2.AutoPostBack = true;
            chk2.Checked = false;
            chk2.ViewStateMode = ViewStateMode.Enabled;


            chk2.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna_c2 = GridView1.HeaderRow.Cells[2].Text;

            chk2.ID = colonna_c2 + e.Row.RowIndex;
            chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c2 + ",false";

            //se è gia stata data la disponibilita metto il checkbox su cliccato 
            if (test.StartsWith("mer") && !test.Contains("B"))
            {
                var saveGame2 = doc
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna_c2.Replace(" ", "_"))
                .Single();
                if (saveGame2.Value != null && saveGame2.Value.Contains(nomeProclamatore))
                {
                    chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c2 + ",true";
                    chk2.Checked = true;
                }
            }
            //-------------------------------------------- 

            chk3.CausesValidation = false;
            chk3.AutoPostBack = true;
            chk3.ViewStateMode = ViewStateMode.Enabled;

            chk3.CheckedChanged += new EventHandler(Cb_CheckedChanged);
            colonna_c3 = GridView1.HeaderRow.Cells[3].Text;
            chk3.ID = colonna_c3 + e.Row.RowIndex;
            chk3.Checked = false;

            chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",false";

            if (test.StartsWith("sab") && !test.Contains("B") || test.StartsWith("dom") && !test.Contains("B"))
            {
                //se è gia stata data la disponibilita metto il checkbox su cliccato 
                var saveGame3 = doc
                .Element(Variables.Mese_Succ(DateTime.Now.Month))
                .Elements(test.Replace(" ", "_"))
                .Elements(colonna_c3.Replace(" ", "_"))
                .Single();

                if (saveGame3.Value != null && saveGame3.Value.Contains(nomeProclamatore))
                {
                    chk3.Checked = true;
                    chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                }
            }
            // if (!test.StartsWith("sab")) // aggiungo il terzo check 
            //     chk3.Enabled = false;

            //PER I GIORNI ECCEZIONALI, INSERISCO IL CHECKBOX ATTIVO SE è GIA STATA DATA LA DISPONIBILITA.........
            if (test.StartsWith("lun") || test.StartsWith("gio") || test.Contains("B")) //quindi sono giorni aggiunti manualmente
            {
                //VISUALIZZO CHE TURNI SONO STATI IMPOSTATI QUANDO è STATO AGGIUNTO IL GIORNO
                var programma = new XmlDocument();
                programma.Load(Server.MapPath(Resources.DisponibilitaXML));
                var mese = programma.DocumentElement.SelectSingleNode(Variables.Mese_Succ(DateTime.Now.Month));
                var giorno = mese.SelectSingleNode(test);
                foreach (XmlNode turni in giorno.ChildNodes)
                {
                    string nome_turno = turni.Name;
                    //se è gia stata data la disponibilita metto il checkbox su cliccato 
                    var saveGame4 = doc
                    .Element(Variables.Mese_Succ(DateTime.Now.Month))
                    .Elements(test.Replace(" ", "_"))
                    .Elements(nome_turno.Replace(" ", "_"))
                    .Single();
                    if (nome_turno == "Mattina_Turno_1" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk1.Checked = true;
                        chk1.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                    if (nome_turno == "Mattina_Turno_2" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk2.Checked = true;
                        chk2.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                    if (nome_turno == "Pomeriggio" && saveGame4.Value != null && saveGame4.Value.Contains(nomeProclamatore))
                    {
                        chk3.Checked = true;
                        chk3.ToolTip = Variables.row_index + "," + test + "," + colonna_c3 + ",true";
                    }
                }
            }


            e.Row.Cells[1].Controls.Add(chk1); // add checkbox to second column
            e.Row.Cells[2].Controls.Add(chk2); // aggiungo il secondo check 
            e.Row.Cells[3].Controls.Add(chk3); //il terzo
        }

    }

    bool isFirstCheckClick = true;
    bool isXmlOpened = false; //variabile per vedere se sto già aggiungendo una disponibilita, serve a non mandare in crash

    private void Cb_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        bool isChecked = checkBox.Checked;
        nome.Text = checkBox.ToString() + isChecked.ToString();
        if (!isXmlOpened && sender != null)
        {
            {
                isXmlOpened = true;
                string info = ((CheckBox)sender).ToolTip.ToString();
                string[] selezione = info.Split(',');
                string data_selezione = selezione[0];

                string turno_selezione = selezione[2];
                id = Request.QueryString["Name"];
                id = id.Replace("+", " ");

                data_selezione = GridView1.Rows[Convert.ToInt32(data_selezione)].Cells[0].Text;
                turno_selezione = turno_selezione.Replace(" ", "_");

                //verifico che è un giorno che ha il pomeriggio se è stato selezionato il pomeriggio
                if (turno_selezione != "Pomeriggio" && turno_selezione != "Mattina_Turno_2" || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("dom") || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("sab") || turno_selezione == "Mattina_Turno_2" && data_selezione.StartsWith("mer"))
                {
                    //l'ho appena selezionato quindi voglio aggiungere il nome
                    if (isChecked || ((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        //da scegliere se usare metodo sopra o sotto 

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);
                        checkBox.Checked = true;
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else //if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    //else Cb_CheckedChanged(checkBox, null);
                    //    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else if (data_selezione.StartsWith("lun") || data_selezione.StartsWith("gio"))
                {
                    if (((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);

                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else
                {
                    //ClientScript.RegisterStartupScript(this.GetType(), "Non esiste", "alert('Non esiste il turno " + turno_selezione + " per il giorno "+ data_selezione +".')", true);

                    // loadData();
                    //   Response.Redirect(
                    //           "AggiungiDisponibilita.aspx?Name=" + id.Replace(" ", "+"));

                }
                isXmlOpened = false;
                // setCheckedAgain(((CheckBox)sender).ID);
            }

        }
    }
}

The checking part here:

        private void Cb_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = ((CheckBox)sender);
        bool isChecked = checkBox.Checked;
        nome.Text = checkBox.ToString() + isChecked.ToString();
        if (!isXmlOpened && sender != null)
        {
            {
                isXmlOpened = true;
                string info = ((CheckBox)sender).ToolTip.ToString();
                string[] selezione = info.Split(',');
                string data_selezione = selezione[0];

                string turno_selezione = selezione[2];
                id = Request.QueryString["Name"];
                id = id.Replace("+", " ");

                data_selezione = GridView1.Rows[Convert.ToInt32(data_selezione)].Cells[0].Text;
                turno_selezione = turno_selezione.Replace(" ", "_");

                //verifico che è un giorno che ha il pomeriggio se è stato selezionato il pomeriggio
                if (turno_selezione != "Pomeriggio" && turno_selezione != "Mattina_Turno_2" || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("dom") || turno_selezione == "Pomeriggio" && data_selezione.StartsWith("sab") || turno_selezione == "Mattina_Turno_2" && data_selezione.StartsWith("mer"))
                {
                    //l'ho appena selezionato quindi voglio aggiungere il nome
                    if (isChecked || ((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        //da scegliere se usare metodo sopra o sotto 

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);
                        checkBox.Checked = true;
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else //if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    //else Cb_CheckedChanged(checkBox, null);
                    //    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else if (data_selezione.StartsWith("lun") || data_selezione.StartsWith("gio"))
                {
                    if (((CheckBox)sender).Checked || selezione[3] == "true")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml

                        var saveGame = doc
                            //.Element("Anno_"+DateTime.Now.Year.ToString())
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione)
                            .Single();

                        saveGame.Value += nome.Text + ",";

                        doc.Save(prog);

                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Aggiunto con successo il giorno'" + data_selezione + ")", true);
                    }
                    else if (selezione[3] == "false")
                    {

                        var doc = XElement.Load(prog); //Percorso file xml
                        var saveGame = doc
                            .Element(Variables.Mese_Succ(DateTime.Now.Month))
                            .Elements(data_selezione)
                            .Elements(turno_selezione.Trim())
                            .Single();
                        string remove = saveGame.Value.ToString();
                        saveGame.Value = remove.Replace((nome.Text + ","), ""); //in teoria dovrebbe rimuovere il nome

                        doc.Save(prog);

                    }
                    else Response.Write(selezione[3] + ((CheckBox)sender).Checked.ToString());
                }
                else
                {
                    //ClientScript.RegisterStartupScript(this.GetType(), "Non esiste", "alert('Non esiste il turno " + turno_selezione + " per il giorno "+ data_selezione +".')", true);

                    // loadData();
                    //   Response.Redirect(
                    //           "AggiungiDisponibilita.aspx?Name=" + id.Replace(" ", "+"));

                }
                isXmlOpened = false;
                // setCheckedAgain(((CheckBox)sender).ID);
            }

        }
    }

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire