C# ASP.NET无法取消选中复选框

C# ASP.NET无法取消选中复选框,c#,asp.net,gridview,checkbox,C#,Asp.net,Gridview,Checkbox,我有一个如此普遍的问题,我真的无法解决。 即使我在网上搜索了很多,我仍然没有找到一个修复方法,所以请不要将它标记为重复,因为它不是。 以下是我试图做的: 我基于XML文件创建了一个GridView,因此我基于它创建了列和行。 每个单元格都有一个复选框,根据xml中的某些变量,该复选框可能是选中的,也可能是不选中的。 我可以使复选框已经选中或取消选中,但这里来了一个问题。 如果一个复选框没有被选中,我点击了它,一切都很顺利,当它被选中,我想取消选中它,复选框只是改变了它的检查,而没有执行它应该做的

我有一个如此普遍的问题,我真的无法解决。 即使我在网上搜索了很多,我仍然没有找到一个修复方法,所以请不要将它标记为重复,因为它不是。 以下是我试图做的: 我基于XML文件创建了一个GridView,因此我基于它创建了列和行。 每个单元格都有一个复选框,根据xml中的某些变量,该复选框可能是选中的,也可能是不选中的。 我可以使复选框已经选中或取消选中,但这里来了一个问题。 如果一个复选框没有被选中,我点击了它,一切都很顺利,当它被选中,我想取消选中它,复选框只是改变了它的检查,而没有执行它应该做的操作(结果是它的状态没有改变)。 我怎样才能解决这个问题?真烦人

下面是一些代码,如果它不是那么可读或制作得不好,很抱歉

    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 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_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);
            }

        }
    }
}
我解释一些方法: loadData()创建包含所需行和列的gridview。 INSERISCIDISPONIBILITAGIDATE()设置复选框值,如果应选中或不选中,以及应选中哪一个。 Cb_CheckedChanged()是触发复选框状态更改的方法。
提前谢谢。

哇,代码太多了。我会说得有点过分。你能把它编译成相关的部分吗?但首先不要使用
Page\u Init
而是
Page\u Load
加载数据。如果复选框返回到它的第一个状态,则意味着您将在回发后再次设置它的默认值。因此,首先在设置复选框值的所有位置设置一个断点,并查看何时执行。我在问题的底部添加了一些方法说明。在您的
Cb_CheckedChanged
中有一个
checkbox.Checked=true。它位于if语句中,该语句仅在复选框已选中时触发。您可能想签出它。我需要根据复选框的状态执行两个不同的操作(如果选中,我取消选中,我需要从Xml文件中删除一个值,反之亦然),这就是原因。如果第一次单击不是选中的复选框,一切都会正常工作
        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);
            }

        }
    }