简体   繁体   中英

Get the text value of the button that was clicked

Trying to get the text value form a button that was clicked, in my head it is something like this...

private void button2_Click(object sender, EventArgs e)
        {
           string s =  thisbutton.text
        }

The object which fired the event is sender , so:

private void button2_Click(object sender, EventArgs e)
{
    string s = (sender as Button).Text;
}

Just cast the sender Object to a Button Object and access the text attribute :

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   string s= btn.Text
}

Should be like this:

private void button2_Click(object sender, EventArgs e)
{
  string s =  this.button2.Text;
}

In every build in event handler there are 2 parameters sender and e . Sender takes reference to that object which fires the event.The second parameter e holds some information about the event(such as the location of pointer and other of this kind) You need only bring it to Button type and get what information you want

try and apply this example in your button event

private void button_click(object sender, EventArgs e)
{
   var getValue = ((Button)sender).Text; //this will get the value of the text using sender
}

The exampels above didn´t work for me, so I tried:

private void button2_click(object sender, EventArgs e)
{
   string s = (sender as Button).Content.ToString();
}

This was asked some time ago and the platform in my case may be a little different to what the OP used but I arrived at the same question for GTK.

I am developing in Xaramin / Visual Studio in OSX using GTK2+, and for me the original accepted answer is close, but yields an error that .Text doesn't exist. In my case, it needs to be Label . This works for me:

protected void Button_Clicked(object sender, EventArgs e)
{
    Button btn = sender as Button;

    lblWhichButton.Text = btn.Label;
    if (btn.Label == "<<<" )
        i--;
    else
        i++;
    lblCounter.Text = "" + i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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