[C#]Can i compare the text of button?

Discussion in 'Mixed Languages' started by carmz, Aug 16, 2012.

  1. carmz

    carmz MDL Senior Member

    Nov 29, 2011
    285
    7
    10
    #1 carmz, Aug 16, 2012
    Last edited: Aug 23, 2012
    [C#] button?

    Hi, problem in text button.
     
  2. AviiNL

    AviiNL MDL Novice

    Aug 6, 2012
    22
    228
    0
    #2 AviiNL, Sep 10, 2012
    Last edited by a moderator: Apr 20, 2017
    Sure you can

    Code:
    if(button1.Text == "somet text"){
        // the text of the button is equal to some text
    }else{
        // the text of the button is something else.
    }
    
     
  3. bunnielovekins

    bunnielovekins MDL Novice

    Sep 16, 2012
    1
    0
    0
    If it's like java, and it usually is, == won't be correct. .Equals would compare strings.
     
  4. Michaela Joy

    Michaela Joy MDL Crazy Lady

    Jul 26, 2012
    3,502
    3,685
    120
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  5. BobSheep

    BobSheep MDL Guru

    Apr 19, 2010
    2,326
    1,358
    90
    #5 BobSheep, Oct 1, 2012
    Last edited by a moderator: Apr 20, 2017
    == is correct for c# and your example is also correct.

    You can use the text as a kind of switch.

    In the OnClick event

    Code:
    if(btn.Text == "Start")
    {
        btn.Text = "Stop";
        timer1.Start();
    }
    else
    {
       btn.Text = "Start";
       timer1.Stop();
    }
     
  6. Tunsdruff

    Tunsdruff MDL Junior Member

    Aug 13, 2011
    78
    34
    0
    #6 Tunsdruff, Oct 3, 2012
    Last edited by a moderator: Apr 20, 2017
    Bobsheep is right, both are correct.

    Nevertheless I would prefer to use Equals... because there you could also define if you want to ignore the case or not

    Code:
    if(String.Equals(btn.Text, "Start", StringComparison.OrdialIgnoreCase))
    {
            btn.Text = "Stop";
            timer1.Start();
    }
    else
    [...]
    
    Well in this case, it doesn't really matter, because the text is set by you...