Wednesday, February 1, 2012

custom validator

// type this part between form tag

Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />
<br /><br />
// type this part in code behind

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
   
if(e.Value.Length == 8)
        e.IsValid
= true;
   
else
        e.IsValid
= false;
}

regular expression validator

// type this part between form tag

4 digit number:<br />
<asp:TextBox runat="server" id="txtNumber" />
<asp:RegularExpressionValidator runat="server" id="rexNumber" controltovalidate="txtNumber" validationexpression="^[0-9]{4}$" errormessage="Please enter a 4 digit number!" />
<br /><br />

range validator

// type this part between form tag

Date:<br />
<asp:TextBox runat="server" id="txtDate" />
<asp:RangeValidator runat="server" id="rngDate" controltovalidate="txtDate" type="Date" minimumvalue="01-01-2006" maximumvalue="31-12-2006" errormessage="Please enter a valid date within 2006!" />
<br /><br />

compare validator

// type this part in between form tag

Small number:<br />
<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />
Big number:
<br />
<asp:TextBox runat="server" id="txtBigNumber" /><br />
<asp:CompareValidator runat="server" id="cmpNumbers" controltovalidate="txtSmallNumber" controltocompare ="txtBigNumber" operator="LessThan" type="Integer" errormessage="The first number should be smaller than the second number!" /><br />

RequiredFieldValidator

//type this part in between form tag

<form id="form1" runat="server">
    Your name:
<br />
   
<asp:TextBox runat="server" id="txtName" />
   
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
   
<br /><br />
   
<asp:Button runat="server" id="btnSubmitForm" text="Ok" onclick="btnSubmitForm_Click" /></form>
//type this part in code behind

protected void btnSubmitForm_Click(object sender, EventArgs e)
{
   
if(Page.IsValid)
    {
        btnSubmitForm.Text
= "My form is valid!";
    }
}

Monday, January 30, 2012

add/delete items in dropdownlist using javascript

// add these code snipets between forms tag

<asp:DropDownList ID="DropDownList1" runat="server" Width="182px"> 
<asp:ListItem value="1" Text ="Approve"></asp:ListItem> 
<asp:ListItem value="2" Text ="Accept"></asp:ListItem> 
<asp:ListItem value="3" Text ="Test1"></asp:ListItem> 
<asp:ListItem value="4" Text ="Test2"></asp:ListItem> 
</asp:DropDownList> 

<input type="button" value="Remove selected item" onclick="JavaScript: DeleteItem();" /> 
<input type="text" id="ddlText" name="ddlText" /> 
<input type="text" id="ddlValue" name="ddlValue" /> 
<input type="button" value="Add item" onclick="JavaScript: AddItem();" /> 
<input type="hidden" id="ddlElements" name="ddlElements" runat="server" /> 
<asp:Button ID="Button1" runat="server" Text="Button" />

// add these code sinpets between header tag

<script type="text/javascript">
    function
DeleteItem()
    {

       
var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>');
       
var optionsList = '';

       
if ( dropDownListRef.value.length > 0 )
        {
           
var itemIndex = dropDownListRef.selectedIndex;
if ( itemIndex >= 0 ) 
            dropDownListRef.remove(itemIndex); 
        } 
        else 
        { 
            alert('Please select an item'); 
            dropDownListRef.focus(); 
            dropDownListRef.select(); 
        } 
          

        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 
        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
     
        if ( optionsList.length > 0 )
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
        document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
    } 


    function AddItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var ddlTextRef = document.getElementById('ddlText'); 
        var ddlValueRef = document.getElementById('ddlValue'); 
        var optionsList = ''; 

        if ( ddlTextRef.value !="" && ddlValueRef.value!="" ) 
        { 
            var option1 = document.createElement("option"); 
            option1.text= ddlValueRef.value; 
            option1.value= ddlTextRef.value ; 
            dropDownListRef.options.add(option1); 
        } 
        else 
            alert('Please enter values'); 
          
        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 

        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
          
        if ( optionsList.length > 0 )
        
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
            document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
       
    } 

</script>
 
In Code behind Page_Load, add following code..
if (IsPostBack)
{
    DropDownList1.Items.Clear();
    string[] DropDownListArray = ddlElements.Value.Trim().Split(';'); 
    
    for (int i = 0; i < DropDownListArray.Length; i = i + 2)
    {
        string itemText = DropDownListArray[i];
        string itemValue = DropDownListArray[i + 1]; 
DropDownList1.Items.Add(new ListItem(itemText, itemValue));
    }

}

string optionsList = string.Empty; 
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
   string optionText = DropDownList1.Items[i].Text;
   string optionValue = DropDownList1.Items[i].Value;
          
    if (optionsList.Length > 0) 
      
    optionsList += ";";
    optionsList += optionText;
    optionsList += ';';
    optionsList += optionValue;
}

ddlElements.Value = optionsList; 

Sunday, January 29, 2012

Using DataList Control

// create a asp.net empty web site
// type this part in between form tag in designer view
<h3>DataList ItemCreated Example</h3>

      <asp:DataList id="ItemsList"
           BorderColor="black"
           CellPadding="5"
           CellSpacing="5"
           RepeatDirection="Vertical"
           RepeatLayout="Table"
           RepeatColumns="3"
           OnItemCreated="Item_Created"
           runat="server">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>

         <AlternatingItemStyle BackColor="Gainsboro">
         </AlternatingItemStyle>

         <HeaderTemplate>

            List of items

         </HeaderTemplate>

         <ItemTemplate>

            Description: <br />
            <%# DataBinder.Eval(Container.DataItem, "StringValue") %>

            <br />

            Price:
            <asp:Label id="PriceLabel"
                 runat="server"/>

         </ItemTemplate>

      </asp:DataList>
// include using System.Collections and using System.Data namesspace in .aspx page
 // type these code snipet in page load even of .aspx page

          if (!IsPostBack)
         {
            ItemsList.DataSource = CreateDataSource();
            ItemsList.DataBind();
         }

// create these two functions in .aspx page

ICollection CreateDataSource()
      {

         // Create sample data for the DataList control.
         DataTable dt = new DataTable();
         DataRow dr;

         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

         // Populate the table with sample values.
         for (int i = 0; i < 9; i++)
         {
            dr = dt.NewRow();

            dr[0] = i;
            dr[1] = "Description for item " + i.ToString();
            dr[2] = 1.23 * (i + 1);

            dt.Rows.Add(dr);
         }

         DataView dv = new DataView(dt);
         return dv;

      }


void Item_Created(Object sender, DataListItemEventArgs e)
      {

         if (e.Item.ItemType == ListItemType.Item ||
             e.Item.ItemType == ListItemType.AlternatingItem)
         {

            // Retrieve the Label control in the current DataListItem.
            Label PriceLabel = (Label)e.Item.FindControl("PriceLabel");

            // Retrieve the text of the CurrencyColumn from the DataListItem
            // and convert the value to a Double.
            Double Price = Convert.ToDouble(
                ((DataRowView)e.Item.DataItem).Row.ItemArray[2].ToString());

            // Format the value as currency and redisplay it in the DataList.
            PriceLabel.Text = Price.ToString("c");

         }

      }
// now execute your website