Reputation: 804
I am trying to get the text value from a button that was clicked. In my head, it looks something like this:
private void button2_Click(object sender, EventArgs e)
{
string s = thisbutton.text
}
Upvotes: 20
Views: 78056
Reputation: 3337
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 Xamarin / 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;
}
Upvotes: 0
Reputation: 2458
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
}
Upvotes: 0
Reputation: 21
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
Upvotes: 1
Reputation: 397
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
}
Upvotes: 5
Reputation: 11389
Should be like this:
private void button2_Click(object sender, EventArgs e)
{
string s = this.button2.Text;
}
Upvotes: 2
Reputation: 23300
The object which fired the event is sender
, so:
private void button2_Click(object sender, EventArgs e)
{
string s = (sender as Button).Text;
}
Upvotes: 48