简体   繁体   English

C#中的ASP.Net复选框

[英]ASP.Net Checkbox in C#

Ok so I am getting into programing in ASP.Net with C#. 好的,我正在使用C#在ASP.Net中进行编程。 I am trying a very simple procedure but it is very buggy. 我正在尝试一个非常简单的程序,但它非常错。 So I have the following ASP code: 所以我有以下ASP代码:

<asp:Button ID="Button1" runat="server" Text="Show Numbers" onclick="Button1_Click1" />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:CheckBox ID="CheckBox1" runat="server" 
            oncheckedchanged="CheckBox1_CheckedChanged" />

I then have the following C# code behind it: 然后我在它后面有以下C#代码:

    int i = 0;
    List<int> Chosen = new List<int>();

    public void Page_Load(object sender, EventArgs e)
    {


    }
    public void Button1_Click1(object sender, EventArgs e)
    {
        if (i == 0)
        {
            TextBox1.Text = "Nothing here!";
        }
        else if (i == 1)
        {
            TextBox1.Text = Chosen[0].ToString();
        }
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (CheckBox1.Checked == true)
        {
            Chosen.Add(1);
            i++;
            CheckBox1.Checked = true;
        }
        else if (CheckBox1.Checked == false)
        {
            Chosen.Remove(1);
            i--;
            CheckBox1.Checked = false;
        }
    }

The goal of the code is to have a checkbox on the screen. 代码的目标是在屏幕上显示一个复选框。 If it is checked I want to add the number 1 to my list (Chosen) also, when I push the button I want the textbox to display the number 1. If the checkbox becomes unchecked I want the number to get removed from the list and when I push the button I want it to display "Nothing here!". 如果选中它我想将数字1添加到我的列表(选择)中,当我按下按钮时我希望文本框显示数字1.如果复选框未选中,我希望从列表中删除该数字当我按下按钮时,我希望它显示“Nothing here!”。

The problem is, sometimes it works and sometimes it doesn't. 问题是,有时它会起作用,有时却不起作用。 For example if I click the box then the button it works. 例如,如果我单击该框,则按钮工作。 Then when I click the button again it says "Nothing Here!" 然后,当我再次点击按钮时,它会显示“Nothing Here!” it should stay as a 1. 它应该保持为1。

You have to set AutoPostBack=true to the CheckBox control markup and also save that list into Session dictinary. 您必须将AutoPostBack=true设置为CheckBox控件标记,并将该列表保存到Session dictinary中。

List<int> Chosen;

public void Page_Load(object sender, EventArgs e)
{
  if(Sesstion["Chosen"]==null)
    {
      Session["Chosen"]=new List<int>();
    }
  Chosen = (List<int>)Session["Chosen"];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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