Saturday, April 25, 2009

Bind asp.net dropdownlist to xml file


Fig: Binding asp.net dropdownlist control to an xml file

Today I am discussing the simple way to bind an asp.net dropdownlist control to an xml file. Besides binding the dropdownlist controls to an xml file, we will also sort the items in the ascending order.

Let us define the xml file first. This consists of Country object with properties ID and Name.

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<ID>1</ID>
<Name>Nepal</Name>
</Country>
<Country>
<ID>2</ID>
<Name>India</Name>
<Country>
<ID>3</ID>
<Name>China</Name>
</Country>
<Country>
<ID>4</ID>
<Name>Bhutan</Name>
</Country>
<Country>
<ID>5</ID>
<Name>USA</Name>
</Country>
</Country>
</Countries>

We place this xml file in the Resources folder of the root of our solution. Now let us define the markup for the asp.net dropdownlist control.

Select from the list of countries:</b>&nbsp;<asp:DropDownList ID="ddlCountry" runat="server"
Width="160px"></asp:DropDownList>

Now in the load event of the page, we read the items from the xml file into a dataset. We will get the DataView for the default table in the dataset, and sort it. The table will consists of as many rows as there are country objects in the xml file. Each row has two columns: ID and Name. Now we can bind this dataview to the dropdownlist control, as in the code (in C#) below.

//page load event handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//call to the function to populate dropdownlist from xml
PopulateDDLFromXMLFile();
}
}

//populates the dropdownlist from xml file
public void PopulateDDLFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/Resources/XMLFile.xml"));

//get the dataview of table "Country", which is default table name
DataView dv = ds.Tables["Country"].DefaultView;
//or we can use:
//DataView dv = ds.Tables[0].DefaultView;

//Now sort the DataView vy column name "Name"
dv.Sort = "Name";

//now define datatext field and datavalue field of dropdownlist
ddlCountry.DataTextField = "Name";
ddlCountry.DataValueField = "ID";

//now bind the dropdownlist to the dataview
ddlCountry.DataSource = dv;
ddlCountry.DataBind();
}

That simple! Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Saturday, March 14, 2009

Check UserName Availability Using XmlHttp in ASP.NET

Most email service providers like gmail, yahoo and hotmail provide live username availability checks. And this trend has been followed by other websites also. This is pretty simple in asp.net to check username availability before user submits the credentials. This saves time as well as increases user interactivity. In this article, I am going to show the simple username availability check mechanism using xmlhttp.

Fig 1: UserName availability check using xmlhttp in asp.net web page

Let's define a simple user registration page. I am just showing the two fields: username and email for demonstration. Please note that this is not a complete code snippet. And I haven't implemented any other validation, for instance there could be one for email validation.

RegisterUser.aspx (add this markup after form element)

<table cellpadding="0" cellspacing="2">

<tr>

<td>User Name:</td>

<td>

<asp:TextBox ID="txtUserName" runat="server" onkeydown="CheckUserNameAvailability();"></asp:TextBox>

<asp:Label ID="lblMsg" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td>Email:</td>

<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td></td>

<td><asp:Button ID="btnRegister" runat="server" Text="Register" /></td>

</tr>

</table>

Now we add the required xmlhttp snippet in the page. This code is to be added before head section of RegisterUser.aspx page.



<script type = "text/javascript">

var xmlhttp;

function CheckUserNameAvailability()

{

xmlhttp=null;

var username=document.getElementById('<%=txtUserName.ClientID %>').value;

if(username="" || username.length<4)

{

document.getElementById("<%=lblMsg.ClientID%>").innerHTML="";

return false;

}



if (window.XMLHttpRequest)

{

// code for all new browsers

xmlhttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// code for IE5 and IE6xmlhttp=

new ActiveXObject("Microsoft.XMLHTTP");

}

if (xmlhttp!=null)

{

xmlhttp.onreadystatechange=state_Change;

xmlhttp.open("GET","CheckUserNameAvailabilityUsingJquery.aspx?UserName="+username,true);

xmlhttp.send(null);

}

else

{

alert("Oops..Your browser does not support XMLHTTP.");

}

}



function state_Change()

{

if (xmlhttp.readyState==4)

{

// 4 = “loaded”

if (xmlhttp.status==200)

{

//request was successful

//check if username is available and message

var lblMesg = document.getElementById("<%=lblMsg.ClientID%>");

if(xmlhttp.responseText=="True")

{

lblMesg.style.color="Green";

lblMesg.innerHTML="Username available.";

}

else

{

lblMesg.innerHTML="Username already in use.";

lblMesg.style.color="Red";

}

}

else

{

alert("Oops..username availability could not be checked.");

}

}

}

</script>

Here goes the page that checks if the username already exists in the database and returns true (if the username does not exists) or false (if the username is already in use).


CheckUserAvailabilityUsingXMLHTTP.aspx

//page load event
protected void Page_Load(object sender, EventArgs e)
{
CheckUserNameAvailability();
}

//checks if the username is available
//for demo, usename has been checked against the asp.net membership system
public void CheckUserNameAvailability()
{
if (Request.Params.Get("UserName") != null)
{
string username = Request.Params.Get("username");
string result = "False";
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
result = "False";
}
else
{
result = "True";
}

Response.Clear();
Response.Write(result);
Response.End();
}
}

Please note the CheckUserNameAvailability.aspx page being called by the xmlhttp code in RegisterUser.aspx page. That's it. Happy Programming!

kick it on DotNetKicks.com  Shout it

Wednesday, March 11, 2009

Watermark Asp.NET Textbox Using JavaScript

Noticed the watermark implemented in custom google search TextBox, like one in the right side of this page (under heading Search asp.net, C#, oracle, SQL Server related tips and solutions)? I am showing the simple and meaningful watermark implementation of a textbox in asp.net web page in this tipsticle (tips + article).

Truly saying, every time I come across a web page, I do naturally look for the searching textbox in the website. And I do usually find it in the left corner or the right upper corner of the website. Not all the search textboxes implement the watermark but they may initialize the text in the search textbox like your search text here or just search. And my enthusiasm always inspires me to click once and then just click out the textbox to see if watermark has been implemented. In my opinion, it is good to implement watermark for the sake of user-interactivity of a website. (And let me praise facebook homepage for this!)

Ok, lets start out with a search textbox in an asp.net web page.


Now we add a javascript code snippet in the page.



function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}
function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

Now is the time to add onblur and onfocus properties to the asp.net TextBox, referencing the relevant javascript function.

string strWatermarkSearch = "Search";
txtSimpleSearch.Text = strWatermarkSearch;
txtSimpleSearch.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermarkSearch + "');");
txtSimpleSearch.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermarkSearch + "');");

We can see the perfect watermark implementation with our search textbox now! Happy Programming!

Liked the post? You can share this post by submitting to dzone,digg,dotnetkicks etc. You can even leave your suggestions as the comment below.


kick it on DotNetKicks.com

Friday, March 6, 2009

Using JavaScript for Validation of Different Date Formats in Asp.NET Web Form

Most often asp.net web applications need to validate date in a form. It is not that easy to play with different format of dates at different places. Mostly the mm/dd/yyyy (alternatively, mm-dd-yyyy) format of date is used. But we may need to go dd/mm/yyyy (alternatively, dd-mm-yyyy) also, and yyyy/mm/dd (alternatively, yyyy-mm-dd) format is no exception too. This article will discuss how to validate date in all these formats using simple yet powerful javascript code snippet.


Fig 1: Using ajax calendar extender to pick date into asp.net textbox in dd-mm-yyyy format



Fig 2: Validation of the date in the textbox in dd-mm-yyyy format on form submit

Let's start with the addition of a TextBox and an ajax calendarextender in a page.


Remember, we need ajax enabled page to use the calendar extender. Note that I have set the format in the calendarextender to dd-MM-yyyy. This will put the date in the targetcontrol (here, txtPurchaseDate) in dd-mm-yyyy format. On client click of the button btnSubmit, the javascript function ValidateForm() will validate the date in the textbox. If it is not in dd-mm-yyyy format, a message will be alerted as in the figures above.

Here are the functions Validateform() and validateInputDate().

function ValidateForm()
{
if(document.getElementById("txtPurchaseDate"))
{
if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false)
{
alert("Please input purchase date in the format dd-mm-yyyy.");
return false;
}
}
}



//Validates date in the format dd-mm-yyyy (e.g. 19-10-2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

Now we can change the validateInputDate() date validation function to validate other date formats. Listed below are the functions for validating different date formats.


//Validates date in the format dd/mm/yyyy (e.g. 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


//Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format mm/dd/yyyy (e.g. 10/19/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd (e.g. 2009-10-19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy/mm/dd (e.g. 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

Happy Programming!
Liked the post? You can kick it on DotNetKicks.com and and

Friday, February 27, 2009

Sys.InvalidOperationExceptio in UpdatePanel in asp.net ajax due to control structure



I recently got this error: Sys.InvalidOperationException: Could not find UpdatePanel with ID 'ctl00_QuoteContent_UpdatePanelSiteAddress'. If it is being updated dynamically then it must be inside another UpdatePanel. And I fixed it too! I was using updatepanel in my page to update certain part from the page. I googled much. [I could sagoon too!]. They suggest that disabling event validation in the page would solve the problem. But nope. Some even told that removing UpdateMode="Conditional" for the upatepanel would solve the problem. And nope again!


Why the Sys.InvalidOperationException with the above mentioned error occurred?


This happened to occur because I had tried to access (and modify property of) a control outside the updatepanel's contenttemplate. Let me show this.


Here goes the design page:

1. I have one dropdownlist (ddlAddressType).
2. Now I have a table with a row [row id trAddress]
3. Within this row I have one updatepanel.
4. In the updatepanel's ContenTemplate I have another table in which I have a gridview.
5. I have added ddlAddressType as the asychronous postback control for the updatepanel.

That's all. For quick preview, I want to hide the row trAddress which is outside the updatepanel itself. Got it?

Now see here the code behind page:

//on selected index changed
protected void ddlAddressType_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddlAddressType.SelectedValue.Contains("--"))
{
//Here I had tried to access the row (set visibility false)
trAddress.Visible=false;
}
else
{
//Here I had tried to access the row (set visibility true)
trAddress.Visible=true;
}
}

Clearly, the row I am trying to make invisible is out of the scope of the updatepanel. So the error occurred.


Solution? In my case, I just set the table visible/invisible. Solved! Happy Programming

kick it on DotNetKicks.com

Popular Posts

Recent Articles