簡體   English   中英

C#Windows Form應用程序中每次單擊時按鈕文本的更改

[英]Button Text Change on Every Click in C# Windows Form Application

  • 通過以下方法“ m1”,按鈕上的首次單擊文本應為“ 01”
  • 通過以下方法“ m2”,按鈕的第二次單擊按鈕上的文本應為“ 02”

  • 然后第三次點擊“ 01”

  • 再次點擊“ 02”
  • 依此類推


private void button1_Click(object sender, EventArgs e)
{
}

public void m1()
{
    button1.Text = "01";
}

public void m2()
{
    button1.Text = "02";
}

這可能對您有幫助

public bool dirtyBool = true; //Initialize it on contructor
private void button1_Click(object sender, EventArgs e)
{
    if(dirtyBool)
    {
        button1.Text = "01";
    }
    else
    {
        button1.Text = "02";
    }
    dirtyBool = !dirtyBool;
}

如果要調用該函數,則

private void button1_Click(object sender, EventArgs e)
{
    if(dirtyBool)
    {
        m1()
    }
    else
    {
        m2()
    }
    dirtyBool = !dirtyBool;
}
public Boolean b = true;
    private void button1_Click(object sender, EventArgs e)
    {


        if (b)
        {
            m1();

        }
        else 
        {
            m2();

        }
        b = !b;

    }

您可以嘗試這樣的事情:

private void button1_Click(object sender, EventArgs e)
{
    button1.Text == "01" ? m2() : m1();
}

這樣的事情應該為您工作。

   private bool isEvenClick;
   private void button1_Click(object sender, EventArgs e)
    {
        if (!isEvenClick)
        {
            m1();
            isEvenClick = true;
        }
        else
        {
            m2();
            isEvenClick = false;
        }
    }

    public void m1()
    {
        button1.Text = "01";

    }

    public void m2()
    {
        button1.Text = "02";

    }

方法m1和m2似乎是私有的,但已標記為公開。 這可以通過計算點擊次數來實現。 如果是asp.net,則應將點擊次數存儲在數據庫或會話中。 如果這是WPF,則點擊次數可以存儲在靜態變量中。 該代碼應如下所示。

private void button1_Click(object sender, EventArgs e)
{
  int numOfClicks = GetClickCount();
  button1.Text = numOfClicks % 2 == 0 ? "02" : "01";
}
    private void button1_Click(object sender, EventArgs e)
    {            
        count++;   //increment the variable on every button click that is declared globally 
        if(count%2==0)//checking the condition
            m2();//calling the method if the condition is true
        else  m1(); //else calling another method

    }
    public void m1()//method1
    { button1.Text = "01";}      
    public void m2()//method2
    {button1.Text = "02";}

}

暫無
暫無

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

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