WPF FAQ
Questions and answers in this FAQ have been collected from newsgroup posts, various mailing lists and the employees of Syncfusion.

25. Controls

FAQ Home
   25.1 How to close the browser window on button control click?
   25.2 How to create server controls at runtime?
   25.3 How to change the text color of a linkbutton control?
   25.4 How to dynamically add validator controls?
   25.5 How to change the image button size during runtime?
   25.6 How can I to divide the .aspx page to different parts with different functionality in a neat and organized manner. Is there any control that can do that?
   25.7 How to maintain Scroll Position in any Page Element?
   25.8 DataBinder.Eval imposes performance penalty on code as it uses late bound reflection. How can I replace this calls with explicit calls?
   25.9 What is the difference between User Controls and Custom Controls?
   25.10 How to apply Style to a Web Server control programmatically?
   25.11 How can I disable a button to prevent the user from multiple clicking?
   25.12 Why do I get the error message "Access is denied : <myctrl>" when I try to load a Custom Control?
   25.13 How to pass information between panels. Information entered in one panel should be displayed in other panel?
   25.14 Why do I get error message "The control '_ctl1' of type 'TextBox' must be inside a form label with runat=server" while trying to place a control inside a form dynamically?
   25.15 How to implement mouseover effects in a <asp:image> web server control?
   25.16 Is there a way to set the position of the controls dynamically?
   25.17 How can I set the maximum and minimum value for RangeValidator based on two dates?
   25.18 How to specify the hspace and vspace in a <asp:Image>?
   25.19 How to disable status bar messages for Hyperlink Controls?
   25.20 How to get the list of all System.Web.UI.WebControls in my page?
   25.21 How to set the vertical align of a TableCell programmatically?
   25.22 How to control viewstate on individual controls?
   25.23 What is the Use of the Login Status Control?
   25.24 How can the page be posted to the different URL on a button click?
   25.25 How can we define OnMouseOver Event for the ImageMap control(2.0)?
   25.26 How can the layout of SideBar in Wizard Control in (ASP.NET 2.0) be changed?



25.1 How to close the browser window on button control click?


Method 1. This will cause a postback on button click in response to which we will send some script to close the window.


VB.NET
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     Response.Write("<script>window.close();</script>")
End Sub



C#
private void Button1_Click(object sender, System.EventArgs e)
{     
     Response.Write("<script>window.close();</script>");
}


Method 2. This is preferable since there is no postback involved.


Use the Attribute collections i.e use Attributes of button control to add client side JavaScript code
VB.NET
      Button1.Attributes.Add("OnClick", "window.close();")



C#
      Button1.Attributes.Add("OnClick", "window.close();");



25.2 How to create server controls at runtime?


Here is an example of creating a HyperLink control in code.

VB.NET


Dim hpl As New HyperLink()
hpl.Text="Text"
hpl.NavigateUrl="http://www.syncfusion.com"'
hpl.ID="theID"
Page.Controls(1).Controls.Add(hpl)



C#
HyperLink hpl = new HyperLink();
hpl.Text="Text";
hpl.NavigateUrl="http://www.syncfusion.com";
hpl.ID="theID";
Page.Controls[1].Controls.Add(hpl);



25.3 How to change the text color of a linkbutton control?


Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-part. There are 2 types of pseudo-elements as “first-line pseudo-element' and 'first-letter pseudo-element'. Pseudo-element is created by a colon followed by pseudo-element's name,e.g:


P:first-line
H1:first-letter


and can be combined with normal classes; e.g:


P.initial:first-line

The first line of this paragraph will be displayed in uppercase letters





25.4 How to dynamically add validator controls?


VB.NET


Dim i As Integer = 1

'Textbox
Dim txtBox As TextBox = New TextBox
txtBox.ControlStyle.CssClass = "textbox"
txtBox.ID = "txtbox" + i.ToString()

'RequiredFieldValidator
Dim rqdVal As RequiredFieldValidator = New RequiredFieldValidator
rqdVal.ID = "rqdVal" + i.ToString()
rqdVal.ControlToValidate = "txtbox" + i.ToString()
rqdVal.ErrorMessage = "Please enter a value"
rqdVal.Display = ValidatorDisplay.Dynamic

'RangeValidator
Dim rngVal As RangeValidator = New RangeValidator
rngVal.ID = "rngVal" + i.ToString()
rngVal.MinimumValue = "1"
rngVal.MaximumValue = "100"
rngVal.ControlToValidate = "txtbox" + i.ToString()
rngVal.Type = ValidationDataType.Double
rngVal.ErrorMessage = " Value should be between 1 and 100"

'Add Controls on the page
Page.Controls(1).Controls.Add(txtBox)
Page.Controls(1).Controls.Add(rqdVal)
Page.Controls(1).Controls.Add(rngVal)


C#


int i=1;

//Textbox
TextBox txtBox = new TextBox();
txtBox.ControlStyle.CssClass = "textbox";
txtBox.ID = "txtbox" + i.ToString();

//RequiredFieldValidator
RequiredFieldValidator rqdVal = new RequiredFieldValidator();
rqdVal.ID = "rqdVal" + i.ToString();
rqdVal.ControlToValidate = "txtbox" + i.ToString();
rqdVal.ErrorMessage = "Please enter a value";
rqdVal.Display =ValidatorDisplay.Dynamic;

//RangeValidator
RangeValidator rngVal = new RangeValidator();
rngVal.ID = "rngVal" + i.ToString();
rngVal.MinimumValue = "1";
rngVal.MaximumValue = "100";
rngVal.ControlToValidate = "txtbox" + i.ToString();
rngVal.Type = ValidationDataType.Double;
rngVal.ErrorMessage = " Value should be between 1 and 100";

//Add Controls on the page
Page.Controls[1].Controls.Add (txtBox);
Page.Controls[1].Controls.Add (rqdVal);
Page.Controls[1].Controls.Add (rngVal);



25.5 How to change the image button size during runtime?


VB.NET


Dim x As New Unit("80px")
Dim y As New Unit("20px")
Dim imagestate as string= "stand"
If imagestate = "stand" then
     imagebutton1.height = x
else
     imagebutton1.height = y
end if


C#


Unit x = new Unit ("80px");
Unit y = new Unit("20px");
string imagestate="stand";
if( imagestate != "stand")
{
     ImageButton1.Height = x;
}
else
{
     ImageButton1.Height = y;
}


For more details Setting Web Server Control Properties Programmatically


25.6 How can I to divide the .aspx page to different parts with different functionality in a neat and organized manner. Is there any control that can do that?


You can use Panel controls, which render as HTML div elements. You can then show or hide the panels by enabling/disabling them. In addition, you can specify different formatting options for different Panels/divs using manual formatting or CSS styles.


25.7 How to maintain Scroll Position in any Page Element?


Check out Jim Ross's article Maintain Scroll Position in any Page Element
The article describes, when using a scrollable Datagrid--one inside an overflow-auto DIV control--how to maintain the user's scroll position inside the DIV across postbacks. It does this using IE behaviors, HTC files.


25.8 DataBinder.Eval imposes performance penalty on code as it uses late bound reflection. How can I replace this calls with explicit calls?


Change the Databinding Expression


<%#DataBinder.Eval (Container.DataItem , "StartDate" , "{0:c}")%>


to In VB.NET


<%#String.Format("{0:d}" , (CType(Container.DataItem, DataRowView))("StartDate"))%>


C#


<%#String.Format("{0:d}" , ((DataRowView)Container.DataItem)["StartDate"])%>



25.9 What is the difference between User Controls and Custom Controls?


User Controls are text files with the extension '.ascx' which enables you to make GUI re-usable controls. Its a text file, which contains a mixture of HTML and scripting. User Controls can be edited in an editor.

On the other hand Custom Controls reside in compiled ( Dll ) assemblies. They are non-GUI but can emit HTML GUI at runtime. Example of Custom Controls would be the sever controls which come bundled with the .NET SDK like DataGrid, Repeater, DataList etc. Custom Controls are always compiled into Dll's and hence require good programming knowledge. The purpose of Custom Controls is also to create re-usable units of code.


25.10 How to apply Style to a Web Server control programmatically?


User Interface


<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 40px; POSITION: absolute; TOP: 64px" runat="server">Syncfusion</asp:TextBox>
<asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 120px" runat="server" Text="Button"></asp:Button>
<asp:CheckBox id="CheckBox1" style="Z-INDEX: 103; LEFT: 40px; POSITION: absolute; TOP: 200px" runat="server" Text="Syncfusion"></asp:CheckBox>


VB.NET
Create a function


Protected Function createStyleForControl(ByVal _forecolor As Color, ByVal _backcolor As Color, ByVal _fontbold As Boolean) As Style
     Dim s As Style = New Style
     s.ForeColor = _forecolor
     s.BackColor = _backcolor
     s.Font.Bold = _fontbold
     Return s
End Function


In Page_Load


Dim textboxStyle As Style = createStyleForControl(Color.Pink, Color.Yellow, False)
Dim buttonStyle As Style = createStyleForControl(Color.Blue, Color.Teal, True)
Dim checkboxStyle As Style = createStyleForControl(Color.AliceBlue, Color.PowderBlue, False)

TextBox1.ApplyStyle(textboxStyle)
Button1.ApplyStyle(buttonStyle)
CheckBox1.ApplyStyle(checkboxStyle)


C#
Create a function


protected     Style createStyleForControl(Color _forecolor ,Color _backcolor ,bool _fontbold )
{
     Style s = new Style();
     s.ForeColor = _forecolor;
     s.BackColor =_backcolor;
     s.Font.Bold = _fontbold;
     return s;
}


In Page_Load


Style textboxStyle=createStyleForControl (Color.Pink, Color.Yellow, false );
Style buttonStyle=createStyleForControl (Color.Blue, Color.Teal, true );
Style checkboxStyle =createStyleForControl (Color.AliceBlue, Color.PowderBlue, false );

TextBox1.ApplyStyle(textboxStyle );
Button1.ApplyStyle (buttonStyle );
CheckBox1.ApplyStyle (checkboxStyle );



25.11 How can I disable a button to prevent the user from multiple clicking?


In the very last line of the button1_Click subroutine, add this line:
VB.NET


Button1.Enabled = False


C#


Button1.Enabled =false;



25.12 Why do I get the error message "Access is denied : <myctrl>" when I try to load a Custom Control?


This is a common problem in ASP.NET. It happens because some program is scanning the Temporary ASP.NET files folders where your assemblies are copied. They have the files open in a mode that prevents ASP.NET itself from using the assembly file.
For solution refer PRB: Access Denied Error When You Make Code Modifications with Index Services Running


25.13 How to pass information between panels. Information entered in one panel should be displayed in other panel?



<asp:Panel id="Panel1" runat="server" Width="271px" Height="41px">
     <TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1">
     <TR>
     <TD>
          <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
     </TD>
     </TR>
     <TR>
     <TD>
     <asp:Button id="Button1" runat="server" Text="Button"></asp:Button></TD>
     </TR>
     </TABLE>
</asp:Panel>
<asp:Panel id="Panel2" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 120px" runat="server"
     Width="176px" Height="91px" Visible="False">
     <asp:Label id="Label1" runat="server"></asp:Label>
</asp:Panel>


On Button Click
VB.NET


Panel2.Visible =true
Label1.Text = TextBox1.Text


C#


Panel2.Visible =true;
Label1.Text = TextBox1.Text ;


Note: Based on the criteria you can hide and show panels


25.14 Why do I get error message "The control '_ctl1' of type 'TextBox' must be inside a form label with runat=server" while trying to place a control inside a form dynamically?


You are probably adding the textbox into the Page directly instead of adding it to the Page's form. Try doing this:

VB.NET


Me.Page.Controls(1).Controls.Add(txtboxctrl)


C#


this.Page.Controls[1].Controls.Add(txtboxctrl);



25.15 How to implement mouseover effects in a <asp:image> web server control?



<asp:Image id="Image1" runat="server" ImageUrl="b2346.jpg"></asp:Image>


VB.NET


Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'")


C#


Image1.Attributes.Add("onmouseover", "this.src='b2456.jpg'");



25.16 Is there a way to set the position of the controls dynamically?


Yes.


<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 116px; POSITION: absolute; TOP: 152px" runat="server"
     Text="Move"></asp:Button>
<asp:RadioButtonList id="RadioButtonList1" style="Z-INDEX: 103; LEFT: 87px; POSITION: absolute; TOP: 27px"
     runat="server" AutoPostBack="True">
     <asp:ListItem Value="10px">10 pixels</asp:ListItem>
     <asp:ListItem Value="100px">100 pixels</asp:ListItem>
     <asp:ListItem Value="200px">200 pixels</asp:ListItem>
</asp:RadioButtonList>


VB.NET


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     ' Put user code to initialize the page here
     If Not Page.IsPostBack Then
      Button1.Style.Add("LEFT", "1px")
     End If
End Sub 'Page_Load

Private Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged
     Button1.Style.Add("LEFT", RadioButtonList1.SelectedItem.Value.ToString())
End Sub 'RadioButtonList1_SelectedIndexChanged


C#


private void Page_Load(object sender, System.EventArgs e)
{
     // Put user code to initialize the page here
     if (!Page.IsPostBack )
     {
          Button1.Style.Add("LEFT", "1px");
     }
}

private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
     Button1.Style.Add("LEFT",RadioButtonList1.SelectedItem.Value.ToString());
}



25.17 How can I set the maximum and minimum value for RangeValidator based on two dates?



<asp:textbox id="TextBox1" runat="server"></asp:textbox>
<asp:rangevalidator id="RangeValidator1" type="Date" controltovalidate="TextBox1" runat="server" errormessage="Not in range" />
<asp:button id="Button1" runat="server" text="Button"></asp:button>


VB.NET


...
Dim dtMinDate As DateTime
Dim dtMaxDate As DateTime
dtMinDate = Convert.ToDateTime("04/25/04")
dtMaxDate = Convert.ToDateTime("10/17/04")
RangeValidator1.MinimumValue = dtMinDate
RangeValidator1.MaximumValue = dtMaxDate
TextBox1.Text = dtMaxDate.ToShortDateString
RangeValidator1.ErrorMessage = "Not in Range of " & dtMinDate.ToShortDateString() & " to " & dtMaxDate.ToShortDateString()


C#


DateTime dtMinDate ;
DateTime dtMaxDate ;
dtMinDate = Convert.ToDateTime("04/25/04");
dtMaxDate = Convert.ToDateTime("10/17/04");
RangeValidator1.MinimumValue = dtMinDate.ToShortDateString () ;
RangeValidator1.MaximumValue = dtMaxDate.ToShortDateString () ;
TextBox1.Text = dtMaxDate.ToShortDateString();
RangeValidator1.ErrorMessage = "Not in Range of " + dtMinDate.ToShortDateString() + " to " + dtMaxDate.ToShortDateString();



25.18 How to specify the hspace and vspace in a <asp:Image>?


VB.NET


Image1.Attributes.Add("hspace", "50")
Image1.Attributes.Add("vspace", "50")


C#


Image1.Attributes.Add("hspace", "50") ;
Image1.Attributes.Add("vspace", "50") ;



25.19 How to disable status bar messages for Hyperlink Controls?


VB.NET


HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;")


C#


HyperLink1.Attributes.Add("onMouseOver", "window.status=' '; return true;") ;



25.20 How to get the list of all System.Web.UI.WebControls in my page?



<asp:Repeater runat="server" DataSource='<%# GetControls() %>' ID="Repeater1">
<HeaderTemplate>
     

</HeaderTemplate>
<ItemTemplate>
     

  •           <%# DataBinder.Eval(Container.DataItem, "Name") %>
         
    </ItemTemplate>
    <FooterTemplate>
         
    </FooterTemplate>
    </asp:Repeater>


    VB.NET


    Protected Function GetControls() As ArrayList
    Dim arrList As New ArrayList()
    Dim t As Type
         For Each t In GetType(Page).Assembly.GetTypes()
              If t.Namespace = "System.Web.UI.WebControls" And GetType(Control).IsAssignableFrom(t) Then
                   arrList.Add(t)
              End If
         Next
    Return arrList
    End Function 'GetControls

    'In Page_Load
    DataBind()


    C#


    protected     ArrayList GetControls()
    {
         ArrayList arrList = new ArrayList();
         foreach (Type t in typeof(Page ).Assembly.GetTypes())
         {
              if (t.Namespace == "System.Web.UI.WebControls" && typeof(Control).IsAssignableFrom(t))
                   arrList.Add(t);
         }
         return arrList;
    }

    //In Page_Load
    DataBind();



    25.21 How to set the vertical align of a TableCell programmatically?


    VB.NET


    Dim tbl As New TableCell()
    'VerticalAlign is enumeration in System.Web.UI.WebControls namespace
    tbl.VerticalAlign = VerticalAlign.Top


    C#


    TableCell tbl=new TableCell();
    //VerticalAlign is enumeration in System.Web.UI.WebControls namespace
    tbl.VerticalAlign = VerticalAlign.Top;



    25.22 How to control viewstate on individual controls?


    You can set the EnableViewState property of the control. You should disable viewstate for any control that doesn't use it to guarantee optimum performance.


    25.23 What is the Use of the Login Status Control?


    The LoginStatus control will allow users to log out if they are currently logged in, and will display a link to the login page if they're logged out.


    <asp:LoginStatus id=" lsUser" runat="server"/>



    25.24 How can the page be posted to the different URL on a button click?


    In 2.0 Button control has a property PostBackURL, which force the page to the different URL on postback.


    <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/Navigate1.aspx" />



    25.25 How can we define OnMouseOver Event for the ImageMap control(2.0)?


    There is no predefined OnMouseOver Event.We can define as follows in the Page_Load Event.

    protected void Page_Load(object sender, EventArgs e)
    {
         ImageHotSpot.Attributes.Add("onmousemove", "MouseOver()");
    }

    Where MouseOver() is the function to be defined in the ClientSide as follows


    <script>
         function MouseOver()
         {
              alert("MouseMoveEvent");
         }
    </script>



    25.26 How can the layout of SideBar in Wizard Control in (ASP.NET 2.0) be changed?


    The sidebar layout cannot be changed. But it can be hidden by setting DisplaySideBar property to False.


    <asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="0"
         BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderWidth="1px" CellPadding="5"
          Font-Names="Verdana" Font-Size="0.8em" Width="347px" DisplaySideBar="False">
    </asp:Wizard>


    © 2001-2009 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap