簡體   English   中英

選中復選框時如何將值放入數組? C#?

[英]how to put a value to an array when a checkbox is checked? c#?

我正在制作一個隨機字符生成器,​​我在form2上有2個表單,form1和form2,那里有復選框,因此如果用戶在我的form1上選中了checkbox1,它將只顯示1個字符,如果用戶選中全部5個復選框,我的form1將生成5個字符。 我在form1上有一個按鈕,它將在生成隨機字符時觸發事件。

字符:'+','-','*','/','%'

我的代碼將如何? 我正在使用WINDOWS FORMS APPLICATION。

圖片在這里:form1: http : //i49.tinypic.com/30bzos8.png form2: http : //i50.tinypic.com/k00ndt.png

        char[] select = new char[] { '+' , '-' , '*' , '/', '%' };
        var rand = new Random();
        char num = select[rand.Next(5)];

這種情況總是很有趣,因為我們不知道您在課堂上所學的內容。 因此,根據我上面上面的評論(似乎在其中提供了矛盾的答案),我將假定Form2是在Form1的構造方法中創建的。 您將需要某種方法來確定要檢查哪些Combobox,我只是對二進制值進行XOR,並且正如我在我的Comment中所說,我將使用ShowDialog啟動Form2並查看返回值以確定是否退出或繼續。 我給你一個簡單而骯臟的例子,這取決於你自己。 如果不是這種情況,您將需要再發布一些代碼

表格1

public partial class Form1 : Form
{
    char[] operators;

    public Form1()
    {
        InitializeComponent();
        Form2 frm2 = new Form2();
        if (frm2.ShowDialog() == DialogResult.OK) //Check for DialogResult Here
        {
            operators = CreateArray(frm2.GetOperators); // Get ComboBox Values from Form2 and Process them
            frm2.Close();                  // Close Form2
        }
        else
            Application.Exit();           // If DialogResult is not OK then exit Form
    }

    private char[] CreateArray( int value)
    {
        string num = "";
        if ((value & 1) == 1)
            num += "+";
        if ((value & 2) == 2)
            num += "-";
        if ((value & 4) == 4)
            num += "*";
        if ((value & 8) == 8)
            num += "/";
        if ((value & 16) == 16)
            num += "%";

        return num.ToCharArray();
    }
}

表格2

public partial class Form2 : Form
{
    int operators;
    public Form2()
    {
        InitializeComponent();
    }

    private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)sender;
        //Method that I used for determining CheckBox State. You can use a boolean array or an Enumeration ....
        if (cb.Text == "Addition")
            operators = operators ^ 1;
        else if (cb.Text == "Subtraction")
            operators = operators ^ 2;
        else if (cb.Text == "Multiplication")
            operators = operators ^ 4;
        else if (cb.Text == "Division")
            operators = operators ^ 8;
        else if (cb.Text == "Modulus")
            operators = operators ^ 16;

    }
    public  int GetOperators       //Property for return value to Form1
    {
        get { return operators; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM