Determine a control's type using a switch statement

  • Thread starter Thread starter Jimmy V
  • Start date Start date
J

Jimmy V

Hi all,

I am a VB programmer who is moving out of the shadows and starting to
code in C#. I would like to know how to determine a control's type
using a swtich statement. In VB i would do something like this:

Private Sub TestControl(ByRef PassedControl as Control)

Select Case True
Case TypeOf PassedControl Is TextBox
'Do something
Case TypeOf PassedControl Is ComboBox
'Do something completely different
Case Else
'Puke
End Select

End Sub

Is there any similar method in C#?

Thanks,

Jimmy V
 
Hello Jimmy,

private void TestControl(ref Control PassedControl)
{
if (true == PassedControl is TextBox) {
} else if (true == PassedControl is ComboBox) {
} else {
}
}

JV> Private Sub TestControl(ByRef PassedControl as Control)
JV> Select Case True
JV> Case TypeOf PassedControl Is TextBox
JV> 'Do something
JV> Case TypeOf PassedControl Is ComboBox
JV> 'Do something completely different
JV> Case Else
JV> 'Puke
JV> End Select
JV> End Sub
JV>
---
WBR,
Michael Nemtsev :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
Jimmy said:
Hi all,

I am a VB programmer who is moving out of the shadows and starting to
code in C#. I would like to know how to determine a control's type
using a swtich statement. In VB i would do something like this:

Private Sub TestControl(ByRef PassedControl as Control)

Select Case True
Case TypeOf PassedControl Is TextBox
'Do something
Case TypeOf PassedControl Is ComboBox
'Do something completely different
Case Else
'Puke
End Select

End Sub

Is there any similar method in C#?

Thanks,

Jimmy V


foreach(Control c in this.Controls)
{
switch (c.GetType().Name)
{
case "TextBox":
//do something
break;
default:
Console.WriteLine(c.GetType().Name);
break;
}
}

Remember controls can contain controls, and don't forget the break
statements.
Ian
 
Michael Nemtsev said:
Hello Jimmy,

private void TestControl(ref Control PassedControl)
{
if (true == PassedControl is TextBox) {
} else if (true == PassedControl is ComboBox) {
} else {
}
}

Note that for the sake of readability, you'd be better off with:

if (PassedControl is TextBox)

There's no need for the comparison with "true" - it just needlessly
complicates things.
 
Hello Jon Skeet [C# MVP],

to be trully I just used online C#->VB.net convertor to regenerate OP code :)

J> Note that for the sake of readability, you'd be better off with:
J>
J> if (PassedControl is TextBox)
J>
J> There's no need for the comparison with "true" - it just needlessly
J> complicates things.
J>
---
WBR,
Michael Nemtsev :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
Back
Top