Access data from Xml file and select Asp.net data using JavaScript in VB.NET

In this article you will learn how to access data from xml file in asp.net application. and you will also learn a small application to select the states corresponding to country without using DropDownList
  • 3795
Download Files:
 
In this article you will learn how to access data from xml file in asp.net application. and you will also learn a small application to select the states corresponding to country without using DropDownList.

These are the following steps to make easy to create this application.

Step1: First off all i have created a website using asp.net 2.o. and create a xml file as follows:

<?xml version="1.0" encoding="utf-8" ?>
<
countries>
    <
country name="INDIA">
        <
state>Andhra Pradesh </state>
        <
state>Arunachal Pradesh </state>
        <
state>Assam</state>
        <
state>Bihar </state>
        <
state>Chhattisgarh </state>
    </
country>

    <country name="USA">
        <
state>Alabama</state>
        <
state>Alaska</state>
        <
state>Arizona</state>
        <
state>Arkansas</state>
        <
state>California</state>
    </
country>

    <country name="RUSSIA">
        <
state>Almetyevsk</state>
        <
state>Arkhangelsk</state>
        <
state>Bryansk</state>
        <
state>Chelyabinsk</state>
        <
state>Dubna</state>
    </
country>

    <country name="MEXICO">
        <
state>Aguascalientes</state>
        <
state> Baja California</state>
        <
state> Baja California Sur</state>
        <
state> Campeche</state>
        <
state> Chiapas</state>
    </country>
</countries>

Step 2: Now create a webpage and write the javascript function for select the states corresponding to country like asfollows:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="TestWebSite._Default" %>
<!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 runat="server">
<
title>Country and states</title>
<
script language="javascript">
var
 XmlHttp;

function CreateXmlHttp()
{
    
try
    
{
        XmlHttp = 
new ActiveXObject("Msxml2.XMLHTTP");
    }
    
catch(e)
    {
        
try
        
{
            XmlHttp = 
new ActiveXObject("Microsoft.XMLHTTP");
        } 
        
catch(oc)
        {
            XmlHttp = 
null;
        }
    }

    //Creating object of XMLHTTP in Mozilla and Safari

    if(!XmlHttp && typeof XMLHttpRequest != "undefined"
    {
        XmlHttp = 
new XMLHttpRequest();
    }
}

function HandleResponse()
{
    
// To make sure receiving response data from server is completed
    
if(XmlHttp.readyState == 4)
    {
        
// To make sure valid response is received from the server, 200 means response received is OK
        
if(XmlHttp.status == 200)
        { 
            
//window.alert("i am here"); 
            
ClearAndSetStateListItems(XmlHttp.responseText);
        }
        
else
        
{
            alert(
"There was a problem retrieving data from the server." );
        }
    }
}

function CountryListOnChange() 
{
    
var countryList = document.getElementById("countrylist");
    
//Getting the selected country from country combo box.
    
var selectedCountry = countryList.options[countryList.selectedIndex].value;
    
var requestUrl = "States.aspx" + "?SelectedCountry=" + encodeURIComponent(selectedCountry);
    CreateXmlHttp();

// If browser supports XMLHTTPRequest object

    if(XmlHttp)
    {
        
//Setting the event handler for the response
        
XmlHttp.onreadystatechange = HandleResponse;
        
//Initializes the request object with GET (METHOD of posting), 
        
XmlHttp.open("GET", requestUrl, true);
        
//Sends the request to server
        
XmlHttp.send(null); 
    }
}

function ClearAndSetStateListItems(countryNode)
{
    
var stateList = document.getElementById("stateList");
    
//Clears the state combo box contents.
    
for (var count = stateList.options.length-1; count >-1; count--)
    {
        stateList.options[count] = 
null;
    }
    
var stateNodes = countryNode.split("-");
    
//window.alert(stateNodes) 
    
var textValue; 
    
var optionItem;
    
//Add new states list to the state combo box.
    
for (var count = 0; count < stateNodes.length; count++)
    {
        textValue = (stateNodes[count]);
        optionItem = 
new Option( textValue, textValue, falsefalse);
        
//window.alert(textValue); 
        //stateList.appendChild(textValue); 
        
stateList.options[stateList.length] = optionItem;
    }
}

</script>
</
head>
<
body>
    <
form id="Form1" method="post" runat="server">
        <
table width="400px" cellpadding="0" cellspacing="0" bordercolor=navy>
            <
tr>
                <
td><b>Country </b></td>
                <
td>
                    <
select onchange="CountryListOnChange();" id="countrylist" name="countrylist" runat="server"style="width: 115px">
                        <
option selected value="Select Country"></option>
                    </
select>
                </
td>
                <
td><b>State </b></td>
                <
td>
                    <
select id="stateList" style="width: 115px">
                        <
option selected></option>
                    </
select>
                </
td>
            </
tr>
        </
table>
    </
form>
</
body>
</
html>

Step 3: Now add the Imports System.Xml namespace.

Step 4: Write the following code-

Imports System.Xml

Namespace TestWebSite

Partial Class _Default
Inherits System.Web.UI.Page

#
Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

'CODEGEN: This method call is required by the Web Form Designer

'Do not modify it using the code editor.

InitializeComponent()

End Sub

#End Region

Dim xmlDoc As New XmlDocument

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim xlist As XmlNodeList
If Page.IsPostBack = False Then
Try
xmlDoc.Load(Server.MapPath("XMLFile.xml"))
xlist = xmlDoc.SelectNodes(
"//countries/country")
For Each xnode As XmlNode In xlist
countrylist.Items.Add(xnode.Attributes(0).InnerText)
Next
Catch
 ex As Exception
Response.Write(ex.Message)
End Try
Else
End
 If
End
 Sub
End
 Class
End
 Namespace

Step 5: Now add a new web page and write the code as follows:

Imports System
Imports System.Web
Imports System.Text
Imports System.IO
Imports System.Collections
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl

Namespace TestWebsite

Partial Class States

Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

InitializeComponent()

End Sub

#End Region

Dim xmlDoc As New XmlDocument
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim xlist As XmlNodeList
Dim xnode As XmlNode
Dim str As String
xmlDoc.Load(Server.MapPath("XMLFile.xml"))
Dim country As String = Request.QueryString("SelectedCountry")
Dim query As String = ("/countries/country[@name='" & country & "']")
xlist = xmlDoc.SelectNodes(query)
Response.Clear()
For Each xnode In xlist
If xnode.HasChildNodes = True Then
For
 Each xn As XmlNode In xnode.ChildNodes
str &= xn.InnerText & 
"-"
Next
End
 If
Next
Response.Clear()
Response.ContentType = 
"text/xml"
Response.Write(str)
Response.End()
End Sub
End
 Class
End
 Namespace

Step 6: Now debug the application. Following output willl be occure.

Image 1.JPG

Figure 1:

Step 7: Select the country like as follows:

Image 2.JPG

Figure 2:

Step 8: When you select country then you can select state like this.

Image 3.JPG

Figure 3:

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.