Sunday, 9 December 2012

ASP.NET Server Controls

Goals:
  • Present simple ASP.NET server controls.
Steps:
  1. Create a new ASP.NET Web Application project in Visual Studio.
  2. Label
    • Add a Label control to the page, modify its Text property.
    • Run the application and take a look at the source code of generated HTML code, note that the Label control was rendered as the span tag:
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml" >
      <head><title>
      
      </title></head>
      <body>
          <form name="form1" method="post" action="Default.aspx" id="form1">
      <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJOTczNTMyNjI5ZGQ+tlIH8gC3zZwd0romTjnrPAqrbg==" />
      </div>
          <div>
              <span id="Label1">This is a label</span>
          </div>
          </form>
      </body>
      </html>
    • An interesting feature of the Label control is ability to define a hot-key for an assigned server control. Add Label and TextBox controls to the page and set the AccessKey and AssociatedControlID properties of the Label:
    • This time, the rendered HTML code contains the Label tag:
          <label for="TextBox1" id="Label2" accesskey="T">
              Label associated with <u>T</u>extBox (use Alt+T to move the focus to 
              the TextBox)
          </label>
          <input name="TextBox1" type="text" id="TextBox1" />
  3. Literal
    • The Literal control is similar to the Label control, but it is rendered as a plain text, without additional tags. Add 2 Literal controls to the page and set their Text property to 'Normal text, <b>bold</b> text'. For the second control set also the Mode property to 'Encode':
    • Check the output HTML code, note the difference in rendering '<' and '>' characters:
       Normal text, <b>bold</b> text.
      <br />
      Normal text, &lt;b&gt;bold&lt;/b&gt; text.
  4. TextBox
    • Add 3 TextBox controls to the page. Leave the first one default. Set the TextMode property of the 2nd one to 'Password'. Set the TextMode property of the 3rd one to 'MultiLine' and set also its Width and Height properties:
    • Look at the generated HTML code and note differences:
       Simple textbox:
      <input name="TextBox2" type="text" id="TextBox2" />
      <br />
      Password textbox:
      <input name="TextBox3" type="password" id="TextBox3" />
      <br />
      Multiline textbox:
      <textarea name="TextBox4" rows="2" cols="20" id="TextBox4" style="height:100px;width:200px;"></textarea>
    • The TextBox control has the TextChanged event triggered when the user moves the focus outside the text box. Add an event handler for this event to the TextBox, in response for this event modify the control's text:
      protected void TextBox2_TextChanged(object sender, EventArgs e)
      {
          TextBox2.Text +=
      " --- MODIFIED!";
      }
    • To make it work, the AutoPostBack property of the TextBox must be changed to true.
    • Run and test the page. Note that the postback is sent when the focus leaves the text box.
    • It is also possible to do something dynamically without a postback, using JavaScript. Add the following code to the page (e.g. between the header and the body of the page):
      <script>
      function
      tbChangedJS() {
          
      return confirm("Should I postback?");
      }
      </script>
      For the TextBox, add the onchange property with JavaScript code calling this method:
      <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True"
          
      ontextchanged="TextBox2_TextChanged"
          onchange="if (!tbChangedJS()) return;" >
      </
      asp:TextBox>
      To understand how it works, see the output HTML code:
      <input name="TextBox2" 
             type="text" 
             onchange="if (!tbChangedJS()) return;setTimeout('__doPostBack(\'TextBox2\',\'\')', 0)" 
             onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" 
             id="TextBox2" />
      Note that the default TextBox's rendering adds some JavaScript code.
  5. Button
    • Add the Button controls to the page, and double-click it in the Design view - the onclick event is automatically generated:

      Add code modifying the Button's text in response for this event:
      protected void Button1_Click(object sender, EventArgs e)
      {
          Button1.Text +=
      " - clicked!";
      }
      Compile and test the page.
    • It is also possible to fire the JavaScript click event before the postback, add the following code to the Button1:
      onclientclick="alert('Hello from the Button1');"
    • It is possible to attach one common ASP.NET click event handler to more than 1 button. Add 2 new buttons and a Literal to the page:
      <asp:Button ID="Button2" Runat="server" Text="Button 2"
          
      OnCommand="Button_Command" CommandName="DoSomething2" />
      <
      asp:Button ID="Button3" Runat="server" Text="Button 3"    OnCommand="Button_Command" CommandName="DoSomething3" />
      <
      asp:Literal ID="Literal3" Runat="server"/>
      Add the following code to the code-behind file:
      protected void Button_Command(Object sender, CommandEventArgs e)
      {
          
      switch (e.CommandName)
          {
              
      case "DoSomething2":
                  Literal3.Text =
      "Button 2 was selected";
                  
      break;
              
      case "DoSomething3":
                  Literal3.Text =
      "Button 3 was selected";
                  
      break;
          }
      }
  6. LinkButton
    • The LinkButton control is a button rendered as a hyperlink:
  7. ImageButton
    • The ImageButton control has all the Button's functionality plus possibility to check coordinates of clicked point. Add the following markup code:
      <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="sample.jpg"
          
      onclick="ImageButton1_Click" />
      <
      asp:Literal ID="Literal4" runat="server"></asp:Literal>
      and C# code:
      protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
      {
          Literal4.Text =
      string.Format("Click at ({0}, {1})", e.X, e.Y);
      }
  8. HyperLink
    • Hyperlinks generated by the HyperLink control can use text or image:
    • This control is rendered as a <a> tag:
       <a id="HyperLink1" href="http://www.google.com">HyperLink to google</a>
      <br />
      <a id="HyperLink2" href="http://www.google.com"><img src="sample.gif" style="border-width:0px;" /></a>
  9. DropDownList
    • Items of the DropDownList control can be initialized statically (the Visual Studio Designer can be used for the Items property, instead of manual writing values):
    • Additionally, the content can be modified dynamically (Default.aspx.cs file):
      protected void Page_Load(object sender, EventArgs e)
      {
          
      if (!IsPostBack)
          {
              DropDownList1.Items.Remove(
      "Second");
              DropDownList1.Items.Add(
      "Fourth");
              DropDownList1.SelectedValue =
      "Third";
          }
      }
      To understand, why checking of the IsPostBack flag is necessary, comment it out, run the page and make some postbacks using other controls - the Fourth item will appear many times on the list.
    • The DropDownList control automatically forces a postback in case of changing its selected value, when the AutoPostBack property is set to true:
      AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"
      Code for the event:
      protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
      {
          DropDownList1.SelectedItem.Text +=
      " - selected!";
      }
  10. ListBox
    • The ListBox control has similar functionality to the DropDownList control, but additionally more than one item can be selected when the SelectionMode property is set to 'Multiple':

      protected void Button4_Click(object sender, EventArgs e)
      {
          
      StringBuilder sb = new StringBuilder("Selected: ");
          
      foreach (int i in ListBox1.GetSelectedIndices())
          {
              sb.AppendFormat(
      "{0} ", ListBox1.Items[i].Text);
          }
          Literal5.Text = sb.ToString();
      }
  11. CheckBox
    • The CheckBox control can also force a postback, when the AutoPostBack property is set to true. Additionally, text alignment can be changed:

      protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
      {
          CheckBox1.Text +=
      " - checked!";
      }
  12. CheckBoxList
    • This control is very helpful when there is a need to display a list of items with checkboxes to allow to select presented items. Instead of creating many CheckBox controls, one CheckBoxList control can be used:
    • Items can be added using the Items property (either statically in the Visual Studio Designer or dynamically in the source code), or bound using the DataSource property:
      protected void Page_Load(object sender, EventArgs e)
      {
          
      if (!IsPostBack)
          {
              DropDownList1.Items.Remove(
      "Second");
              DropDownList1.Items.Add(
      "Fourth");
              DropDownList1.SelectedValue =
      "Third";

              
      string[] items = new string[] { "First", "Second", "Third", "Fourth", "Fifth" };
              CheckBoxList1.DataSource = items;
              CheckBoxList1.DataBind();
          }
      }
      protected void Button5_Click(object sender, EventArgs e)
      {
          StringBuilder sb = new StringBuilder("Selected: ");
          foreach (ListItem li in CheckBoxList1.Items)
          {
              if (li.Selected)
              {
                  sb.AppendFormat("{0} ", li.Text);
              }
          }
          Literal6.Text = sb.ToString();
      }
      Setting the DataSource property does not makes the action of binding data, the DataBind method must be called explicitly.
  13. RadioButton
    • For the RadioButton controls the GroupName property is crucial. For example, in the following code the 1st and 2nd RadioButton controls can be selected simultaneously because their values of the GroupName property differ:
  14. RadioButtonList
    • This control is very similar to the CheckBoxList control, the only difference is that in the RadioButtonList it is impossible to select more than 1 item.
  15. BulletedList  
    • The BulletedList control can be an alternative for the RadioButtonList control. It can display a list of items:

      and catch a click on an item:
      protected void BulletedList1_Click(object sender, BulletedListEventArgs e)
      {
          Literal7.Text =
      "Clicked: " + BulletedList1.Items[e.Index].Text;
      }
  16. Image
    • The Image control is rendered as a static image, which does not support handling user clicks.
  17. ImageMap
    • It enables to turn an image into a navigation menu. Rectangle, circle, and polygon hotspots (easy to define using the Visual Studio Designer) can be used to catch clicks. In the following example one rectangle (pointing to http://www.google.com ) and one circle hotspot (causes a postback) are used:

      Note, that the red circle and rectangle are statically drawn on the image.
      protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
      {
          
      if (e.PostBackValue == "theCircle")
          {
              Literal8.Text =
      "Circle clicked!";
          }
      }
[Source code]

No comments :