How can I get this VB code to work in C # using the same variable?

I am trying to figure out how to convert the following code sample to C # using the same implicit definition as VB. I know that I can define a button and a common control as two objects and make it work, but I would like to use the same "ctlHTML" variable in C # as VB. Can anyone help with this?

Sub MySub(varInput As String, pnl As Panel) Dim ctlHTML = Nothing Select Case varInput Case "btn" ctlHTML = New HtmlButton Case "lbl" ctlHTML = New HtmlGenericControl() End Select With ctlHTML .Style.Add("font-size", "14px") End With pnl.Controls.Add(ctlHTML) End Sub 
+7
source share
3 answers

You cannot directly convert the code. You will have to specify the type of variable. The highest class in the inheritance chain that supports all your members will be HtmlControl :

 HtmlControl control = null; switch(varInput) { case "btn": control = new HtmlButton(); break; case "lbl": control = new HtmlGenericControl(); break; } if(control != null) { control.Style.Add("font-size", "14px"); pnl.Controls.Add(control); } 
+4
source

To change the Style property, the minimum value of the control must be HtmlControl . Therefore, you need to declare the ctlHtml variable as this type.

You should also check if ctlHtml properly initialized.

I believe your code should look something like this:

 public void MySub(string varInput, Panel pnl) { HtmlControl ctlHtml; switch(varInput) { case "btn": ctlHtml = new HtmlButton(); break; case "lbl": ctlHtml = new HtmlGenericControl(); break; default: ctlHtml = null; break; } if (ctlHtml != null) { ctlHtml.Style.Add("font-size", "14px"); pnl.Controls.Add(ctlHtml); } } 
+4
source

Since HtmlGenericControl and HtmlButton both inherit from HtmlControl , you can declare ctlHTML as this type ( HtmlControl ) and it will work.

See here: http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlcontrol.aspx

+1
source

All Articles