Convert Type.

  • Thread starter Thread starter Anibal
  • Start date Start date
A

Anibal

How do i convert an object variable to a Button one.
I have the following code in VB wich works fine:

Sub Button1Click(sender As Object, e As System.EventArgs)
Dim btn as Button = Convert.ChangeType(sender,GetType(Button))
MessageBox.Show(btn.Text)
End Sub

How can i reproduce the same behaivour in C#?
Thanks.
 
Button button = (Button)sender;
MessageBox.Show(button.Text);

Technically you are not "converting" as the object is already referencing a
button type. Rather you are "casting" it.
 
Anibal said:
How do i convert an object variable to a Button one.
I have the following code in VB wich works fine:

Sub Button1Click(sender As Object, e As System.EventArgs)
Dim btn as Button = Convert.ChangeType(sender,GetType(Button))
MessageBox.Show(btn.Text)
End Sub

How can i reproduce the same behaivour in C#?
Thanks.

I don't know VB well but I think casting is what you want.

public void Button1Click(Object sender, EventArgs e) {
Button btn = (Button) sender; // casting from Object to Button.
MessageBox.Show(btn.Text);
}

I'm hopped up on cough medicine, so I may be inaccurate here, but I
think this is what you're trying to do.

jeremiah
 
Thank you very much.


Andrew Robinson said:
Button button = (Button)sender;
MessageBox.Show(button.Text);

Technically you are not "converting" as the object is already referencing
a button type. Rather you are "casting" it.
 
Anibal said:
How do i convert an object variable to a Button one.
I have the following code in VB wich works fine:

Sub Button1Click(sender As Object, e As System.EventArgs)
Dim btn as Button = Convert.ChangeType(sender,GetType(Button))
MessageBox.Show(btn.Text)
End Sub

How can i reproduce the same behaivour in C#?
Thanks.
You can also use the 'as' operator.

Button b = sender as Button;

However, this will not throw an invalidcastexception, rather it will
return null if the cast fails.

JB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top