Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts
1

Asp.Net Bind Populate DropDownList With JQuery And XML

In this example i'm explaining How To Populate Or Bind DropDownList With JQuery And XML In Asp.Net.
bind populate dropdownlist with jquery and xml

Add jquery library reference in head section and place one dropdown on the page.

Add one list item with select as it's value.

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  </asp:DropDownList>
   4:   
   5:  <asp:Label ID="Label1" runat="server" Text=""/>


Following is the Cities.xml file i'm using to bind dropdownlist using jquery.


  
    Mumbai
    1
  
    
    Delhi
      2
  
  
    Banglore
    3
  
  
    Chennai
    4
  

Add this script in head section of page.

  

Build and run the code.

1

Populate Bind DropDownList From XML File In Asp.Net

This Example explains how to Populate Or Bind DropDownList With XML File Data In Asp.Net In 3/n Tier Architecture Using C# And VB.

Populate Bind DropDownList From XML File
Place one DropdownList on the page.

<asp:DropDownList ID="DropDownList1" 
                  runat="server" 
                  onselectedindexchanged
  ="DropDownList1_SelectedIndexChanged">


XML Data Can be in various formats, i'll use 3 different ones shown below.


Sample 1.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail>
   4:      <ID>1</ID>
   5:      <Name>Csharp</Name>
   6:    </Detail>
   7:    <Detail>
   8:      <ID>2</ID>
   9:      <Name>AspNet</Name>
  10:    </Detail>
  11:    <Detail>
  12:      <ID>3</ID>
  13:      <Name>Articles</Name>
  14:    </Detail>
  15:  </Employees>

Another format can be
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail ID="1" Name="Csharp"></Detail>
   4:    <Detail ID="2" Name="AspNet"></Detail>
   5:    <Detail ID="3" Name="Articles"></Detail>
   6:  </Employees>

Writing following code in Page_Load event is enough to bind dropdownlist from these types of XML data.

C#
using System.Data;
using System.Xml;
protected void Page_Load(object sender, EventArgs e)
{
        DataSet dsXml = new DataSet();
        dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"));
        DropDownList1.DataSource = dsXml;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
        DropDownList1.AutoPostBack = true;
}

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim dsXml As New DataSet()
 dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"))
 DropDownList1.DataSource = dsXml
 DropDownList1.DataTextField = "Name"
 DropDownList1.DataValueField = "ID"
 DropDownList1.DataBind()
 DropDownList1.AutoPostBack = True
End Sub


If XML format is mix of above two.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Details>
   3:    <Name ID="1">Amit</Name>
   4:    <Name ID="2">Jain</Name>
   5:    <Name ID="3">Csharp</Name>
   6:    <Name ID="4">AspNet</Name>
   7:    <Name ID="5">Articles</Name>
   8:  </Details>

We need to loop through nodes to fine value of ID attribute.

C#
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/XMLFile.xml"));
            XmlNodeList list = doc.GetElementsByTagName("Name");
            foreach (XmlNode node in list)
            {
                ListItem lItem = new ListItem(node.InnerText, node.Attributes["ID"].Value);
                DropDownList1.Items.Add(lItem);
            }
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }

VB
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  Dim doc As New XmlDocument()
  doc.Load(Server.MapPath("~/XMLFile.xml"))
  Dim list As XmlNodeList = doc.GetElementsByTagName("Name")
  For Each node As XmlNode In list
   Dim lItem As New ListItem(node.InnerText, node.Attributes("ID").Value)
   DropDownList1.Items.Add(lItem)
  Next
  DropDownList1.Items.Insert(0, "--Select--")
  DropDownList1.SelectedIndex = 0
  DropDownList1.AutoPostBack = True
 End If
End Sub


To Bind DropDownList in 3 tier architecture environment, add to new class files in App_Code folder of application and name them DataLayer.cs and BusinessLayer.cs

Write Following code in these class respectively.

Data Access Layer (DAL)
using System.Web;
using System.Xml;
public class DataLayer
{
 public DataLayer()
 {
 }
    public XmlDocument GetXmlData()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~/XMLFile.xml"));
        return doc;
    }
}

Business Access Layer (BAL)
using System.Web.UI.WebControls;
using System.Xml;
public class BusinessLayer
{
 public BusinessLayer()
 {
    }
    public ListItemCollection BindDropDownList()
    {
        ListItemCollection ddlItems = new ListItemCollection();
        DataLayer objDAL = new DataLayer();
        XmlNodeList list = objDAL.GetXmlData().GetElementsByTagName("Name");
        foreach (XmlNode node in list)
        {
           ListItem item = new ListItem(node.InnerText, node.Attributes["ID"].Value);
           ddlItems.Add(item);
            
        }
        return ddlItems;
    }
}

Write code in Page_Load event of aspx page (Presentation Layer)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BusinessLayer objBAL = new BusinessLayer();
            DropDownList1.DataSource = objBAL.BindDropDownList();
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }


0

DataTable Does Not Support Schema Inference From Xml Error

DataTable Does Not Support Schema Inference From Xml

DataTable does not support schema inference from Xml
If you are trying to read XML File Data Into DataTable and getting schema inference error then you may have written the code as mentioned below.

"DataTable does not support schema inference from Xml"


C# CODE
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath("~/Employees.xml");
        DataTable dtXml = new DataTable("Employee");
        
        dtXml.ReadXml(xmlFilePath);
        GridView1.DataSource = dtXml;
        GridView1.DataBind();
    }

To fix this error, you need to create columns in datatable matching with your XML file elements to Read XML File Into DataTable successfully by following code mentioned in the link.

4

Read XML File Into DataTable In ASP.NET C# VB

In this example i'm explaining how to Read XML File Data Into DataTable In Asp.Net Using C# And VB.NET

I have created a XML File which contains FirstName, LastName and Location sub elements which is shown below.

Read XML File Data Into DataTable C# VB.NET ASP.NET

Element name Employee must be passed while creating object of DataTable.







XML Data

Amit Jain Mumbai User 1 Delhi User 2 Bangalore

Write below mentioned code in Click event of Read Button.

C# CODE
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Employees.xml");
        //Employee Must match with the element name in 
        //your file
        DataTable dt = new DataTable("Employee");
        
        //Add Columns in datatable
        //Column names must match XML File nodes
        dt.Columns.Add("firstname", typeof(System.String));
        dt.Columns.Add("lastname", typeof(System.String));
        dt.Columns.Add("location", typeof(System.String));
        
        //Read XML File And Display Data in GridView
        dt.ReadXml(filePath);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.NET CODE
Protected Sub btnReadXmlFile_Click(sender As Object, e As EventArgs)
 Dim filePath As String = Server.MapPath("~/Employees.xml")
 'Employee Must match with the element name in 
 'your file
 Dim dt As New DataTable("Employee")

 'Add Columns in datatable
 'Column names must match XML File nodes
 dt.Columns.Add("firstname", GetType(System.String))
 dt.Columns.Add("lastname", GetType(System.String))
 dt.Columns.Add("location", GetType(System.String))

 'Read XML File And Display Data in GridView
 dt.ReadXml(filePath)
 GridView1.DataSource = dt
 GridView1.DataBind()
End Sub

1

Read XML Data Into DataSet In Asp.Net C# VB.NET

In this code example i'm explaining how to Read XML Data Into DataSet Using C# And VB.NET In Asp.Net.

Read Xml Data Into DataSet C# VB.NET Asp.Net


For this i have placed one GridView on the aspx page to display after reading Data from XML File on server in Click Event of Read Button.

XML File contains firstname, lastname and location sub elements under employee element.



C# CODE
using System.Data;
using System.IO;
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Employees.xml");
        DataSet dsData = new DataSet();
        //If you don't want to read through FileStream then comment below line
        FileStream fsReadSchema = new FileStream(filePath, FileMode.Open);
        dsData.ReadXml(fsReadSchema);
        fsReadSchema.Close();
        GridView1.DataSource = dsData;
        GridView1.DataBind();
    }

VB.NET CODE
Protected Sub btnReadXmlFile_Click(sender As Object, e As EventArgs)
 Dim filePath As String = Server.MapPath("~/Employees.xml")
 Dim dsData As New DataSet()
 'If you don't want to read through FileStream then comment below line
 Dim fsReadSchema As New FileStream(filePath, FileMode.Open)
 dsData.ReadXml(fsReadSchema)
 fsReadSchema.Close()
 GridView1.DataSource = dsData
 GridView1.DataBind()
End Sub

Build and run the code.

0

Read Write XML File Data In Asp.Net C# VB

In this example i'm explaining how to Read And Write XML File Data In Asp.Net Using C# VB.NET. I have created a aspx page with three textbox to enter Details, Two buttons to read and write Data in click event of buttons.

I'm using Label control to display XML data after reading it.

Read write xml file in asp.net using c# vb.Net


HTML SOURCE OF PAGE
   1:  <div>
   2:  Employee Details:
   3:   
   4:  Name:
   5:  <asp:Textbox id="txtName" runat="server"/>
   6:   
   7:  Department:  
   8:  <asp:Textbox id="txtDept" runat="server"/>
   9:   
  10:  Location:  
  11:  <asp:Textbox id="txtLocation" runat="server"/>
  12:   
  13:  <asp:Button ID="btnWrite" runat="server" 
  14:              Text="Write XML File" 
  15:              onclick="btnWrite_Click"/>
  16:   
  17:  Read Data :
  18:  <asp:Button id="btnRead" text="Read XML File" 
  19:              runat="server" 
  20:              onclick="btnRead_Click"/>
  21:   
  22:  <asp:label id="lblMsg" runat="server"/>
  23:   
  24:  </div>

Write below mentioned code in click event of respective buttons.

C# CODE
using System;
using System.Xml;
using System.Text;

protected void btnRead_Click(object sender, EventArgs e)
    {
        ReadXmlFile(Server.MapPath("EmployeeDetails.xml"));
    }
    protected void btnWrite_Click(object sender, EventArgs e)
    {
        XmlTextWriter xWriter = new XmlTextWriter(Server.MapPath("EmployeeDetails.xml"), Encoding.UTF8);
        xWriter.WriteStartDocument();
        //Create Parent element
        xWriter.WriteStartElement("EmployeeDetails");
        //Create Child elements
        xWriter.WriteStartElement("Details");
        xWriter.WriteElementString("Name", txtName.Text);
        xWriter.WriteElementString("Department", txtDept.Text);
        xWriter.WriteElementString("Location", txtLocation.Text);
        xWriter.WriteEndElement();

        //End writing top element and XML document
        xWriter.WriteEndElement();
        xWriter.WriteEndDocument();
        xWriter.Close();
    }

    protected void ReadXmlFile(string fileName)
    {
        string parentElementName = "";
        string childElementName = "";
        string childElementValue = "";
        bool element = false;
        lblMsg.Text = "";
        
        XmlTextReader xReader = new XmlTextReader(fileName);
        while (xReader.Read())
        {
            if (xReader.NodeType == XmlNodeType.Element)
            {
                if (element)
                {
                   parentElementName = parentElementName + childElementName + "
"; } element = true; childElementName = xReader.Name; } else if (xReader.NodeType == XmlNodeType.Text | xReader.NodeType == XmlNodeType.CDATA) { element = false; childElementValue = xReader.Value; lblMsg.Text = lblMsg.Text + "" + parentElementName + "
" + childElementName + "

" + childElementValue; parentElementName = ""; childElementName = ""; } } xReader.Close(); }

VB.NET CODE
Protected Sub btnRead_Click(sender As Object, e As EventArgs)
 ReadXmlFile(Server.MapPath("EmployeeDetails.xml"))
End Sub
Protected Sub btnWrite_Click(sender As Object, e As EventArgs)
 Dim xWriter As New XmlTextWriter(Server.MapPath("EmployeeDetails.xml"), Encoding.UTF8)
 xWriter.WriteStartDocument()
 'Create Parent element
 xWriter.WriteStartElement("EmployeeDetails")
 'Create Child elements
 xWriter.WriteStartElement("Details")
 xWriter.WriteElementString("Name", txtName.Text)
 xWriter.WriteElementString("Department", txtDept.Text)
 xWriter.WriteElementString("Location", txtLocation.Text)
 xWriter.WriteEndElement()

 'End writing top element and XML document
 xWriter.WriteEndElement()
 xWriter.WriteEndDocument()
 xWriter.Close()
End Sub

Protected Sub ReadXmlFile(fileName As String)
 Dim parentElementName As String = ""
 Dim childElementName As String = ""
 Dim childElementValue As String = ""
 Dim element As Boolean = False
 lblMsg.Text = ""

 Dim xReader As New XmlTextReader(fileName)
 While xReader.Read()
  If xReader.NodeType = XmlNodeType.Element Then
   If element Then
    parentElementName = parentElementName & childElementName & "
" End If element = True childElementName = xReader.Name ElseIf xReader.NodeType = XmlNodeType.Text Or xReader.NodeType = XmlNodeType.CDATA Then element = False childElementValue = xReader.Value lblMsg.Text = lblMsg.Text + "" & parentElementName & "
" & childElementName & "

" & childElementValue parentElementName = "" childElementName = "" End If End While xReader.Close() End Sub


Download Sample Code



9

Asp.Net AdRotator With Timer Rotate Ads Without Refresh

AdRotator Control With Timer Example In Asp.Net Ajax To Rotate Advertisements Ads Without Refreshing The Page.

Asp.Net AdRotator With timer to rotate ads without refreshing the page
AdRotator control is used to display ads on asp.net website.

Ads are changed when user reload or refresh the page, but using ajax and timer we can rotate them without refreshing.

Create a new website in visual studio and add a new folder named Ads and place some images in it.

AdRotator control display advertisements from XML file

For this right click in solution explorer > Add New Item > XML File.

Name it advertisement.xml and write following info in it.


   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Advertisements>
   3:    <Ad>
   4:      <ImageUrl>~/Ads/1.jpg</ImageUrl>
   5:      <NavigateUrl>http://www.google.com</NavigateUrl>
   6:      <AlternateText>AdRotator Control sample ads
   7:      </AlternateText>
   8:      <Impressions>20</Impressions>
   9:      <Keyword>Asp.Net</Keyword>
  10:    </Ad>
  11:    <Ad>
  12:      <ImageUrl>~/Ads/2.jpg</ImageUrl>
  13:      <NavigateUrl>http://csharpdotnetfreak.blogspot.com
  14:      </NavigateUrl>
  15:      <AlternateText>AdRotator Control sample ads
  16:      </AlternateText>
  17:      <Impressions>30</Impressions>
  18:      <Keyword>Asp.Net</Keyword>
  19:    </Ad>
  20:   </Advertisements>

Place AdRotator control on the aspx page and configure it as mentioned below.

   1:  <asp:AdRotator ID="AdRotator1" runat="server" 
   2:                 AdvertisementFile="~/App_Data/advertisement.xml"
   3:                 KeywordFilter="Asp.Net">
   4:  </asp:AdRotator>

Set AdvertisementFile property to the XML file we created earlier and set KeywordFilter to keywords on which we want to show ads, these can be channel keywords or banner size keywords but they must match with keywords in XML file.

To change ads on regular interval we need to put AdRotator control in Ajax Update Panel with a timer control in it as mentioned below.

   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:ScriptManager ID="ScriptManager1" 
   4:                     runat="server">
   5:  </asp:ScriptManager>
   6:   
   7:  <asp:Timer ID="Timer1" runat="server" 
   8:             Interval="500">
   9:  </asp:Timer>
  10:   
  11:  <asp:UpdatePanel ID="UpdatePanel1" 
  12:                   runat="server">
  13:  <Triggers>
  14:  <asp:AsyncPostBackTrigger ControlID="Timer1" 
  15:                            EventName="Tick" />
  16:  </Triggers>
  17:   
  18:  <ContentTemplate>
  19:  <asp:AdRotator ID="AdRotator1" runat="server" 
  20:                 AdvertisementFile="~/App_Data/advertisement.xml"
  21:                 KeywordFilter="Asp.Net">
  22:  </asp:AdRotator>
  23:  </ContentTemplate>
  24:  </asp:UpdatePanel>
  25:  </div>
  26:  </form>

Build and run the code.

Download Sample Code



5

GridView XML Edit Delete Insert Update

GridView XML Edit Delete Insert Update. In this example i'm explaining how to Edit Delete Insert and update XML file data in GridView using C# and VB.Net in Asp.Net.

GridView Xml Edit Delete Insert Update Asp.Net
I have created a XML file with three fields Firstname,LastName and Location.

XML file looks like mentioned below.



  
Amit Jain Mumbai
User 3 Noida
User 4 Bangalore

I have placed one gridview on aspx page and three textbox in editItemTemplate of gridview for editing, one button and three textbox in Footer Template for Inserting new records in XML file.

HTML SOURCE OF PAGE
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" ShowFooter="True" 
              onrowcancelingedit="GridView1_RowCancelingEdit" 
              onrowdeleting="GridView1_RowDeleting" 
              onrowediting="GridView1_RowEditing" 
              onrowupdating="GridView1_RowUpdating" 
              onrowcommand="GridView1_RowCommand">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
 
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" Text='<%#Eval("FirstName") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%#Bind("FirstName")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btn" runat="server" Text="Insert" CommandName="InsertXMLData"/>
<asp:TextBox ID="txtFirstNameInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" Text='<%#Eval("LastName") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastNameInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" Text='<%#Bind("Location") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLocationInsert" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


c# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            BindGridView();
    }
    protected void BindGridView()
    {
        DataSet dsXML = new DataSet();
        dsXML.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        GridView1.DataSource = dsXML;
        GridView1.DataBind();
        GridView1.ShowFooter = true;
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        BindGridView();
        DataSet dsGrid = (DataSet)GridView1.DataSource;
        dsGrid.Tables[0].Rows[GridView1.Rows[e.RowIndex].DataItemIndex].Delete();
        dsGrid.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.ShowFooter = false;
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int index = GridView1.Rows[e.RowIndex].DataItemIndex;
        string firstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
        string lastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
        string location = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLocation")).Text;
        GridView1.EditIndex = -1;
        BindGridView();
        DataSet dsUpdate = (DataSet)GridView1.DataSource;
        dsUpdate.Tables[0].Rows[index]["FirstName"] = firstName;
        dsUpdate.Tables[0].Rows[index]["LastName"] = lastName;
        dsUpdate.Tables[0].Rows[index]["Location"] = location;
        dsUpdate.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGridView();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
        if(e.CommandName == "InsertXMLData")
        {
        string firstname = ((TextBox)GridView1.FooterRow.FindControl("txtFirstNameInsert")).Text;
        string lastname = ((TextBox)GridView1.FooterRow.FindControl("txtLastNameInsert")).Text;
        string location = ((TextBox)GridView1.FooterRow.FindControl("txtLocationInsert")).Text;
        BindGridView();
        DataSet dsInsert = (DataSet)GridView1.DataSource;
        DataRow drInsert = dsInsert.Tables[0].NewRow();
        drInsert["FirstName"] = firstname;
        drInsert["LastName"] = lastname;
        drInsert["Location"] = location;
        dsInsert.Tables[0].Rows.Add(drInsert);
        dsInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"));
        BindGridView();
        }
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not Page.IsPostBack Then
  BindGridView()
 End If
End Sub
Protected Sub BindGridView()
 Dim dsXML As New DataSet()
 dsXML.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 GridView1.DataSource = dsXML
 GridView1.DataBind()
 GridView1.ShowFooter = True
End Sub

Protected Sub GridView1_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
 BindGridView()
 Dim dsGrid As DataSet = DirectCast(GridView1.DataSource, DataSet)
 dsGrid.Tables(0).Rows(GridView1.Rows(e.RowIndex).DataItemIndex).Delete()
 dsGrid.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 BindGridView()

End Sub
Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
 GridView1.ShowFooter = False
 GridView1.EditIndex = e.NewEditIndex
 BindGridView()
End Sub
Protected Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
 Dim index As Integer = GridView1.Rows(e.RowIndex).DataItemIndex
 Dim firstName As String = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txtFirstName"), TextBox).Text
 Dim lastName As String = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txtLastName"), TextBox).Text
 Dim location As String = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txtLocation"), TextBox).Text
 GridView1.EditIndex = -1
 BindGridView()
 Dim dsUpdate As DataSet = DirectCast(GridView1.DataSource, DataSet)
 dsUpdate.Tables(0).Rows(index)("FirstName") = firstName
 dsUpdate.Tables(0).Rows(index)("LastName") = lastName
 dsUpdate.Tables(0).Rows(index)("Location") = location
 dsUpdate.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
 BindGridView()

End Sub
Protected Sub GridView1_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
 GridView1.EditIndex = -1
 BindGridView()
End Sub

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)

 If e.CommandName = "InsertXMLData" Then
  Dim firstname As String = DirectCast(GridView1.FooterRow.FindControl("txtFirstNameInsert"), TextBox).Text
  Dim lastname As String = DirectCast(GridView1.FooterRow.FindControl("txtLastNameInsert"), TextBox).Text
  Dim location As String = DirectCast(GridView1.FooterRow.FindControl("txtLocationInsert"), TextBox).Text
  BindGridView()
  Dim dsInsert As DataSet = DirectCast(GridView1.DataSource, DataSet)
  Dim drInsert As DataRow = dsInsert.Tables(0).NewRow()
  drInsert("FirstName") = firstname
  drInsert("LastName") = lastname
  drInsert("Location") = location
  dsInsert.Tables(0).Rows.Add(drInsert)
  dsInsert.WriteXml(Server.MapPath("~/App_Data/XMLFile.xml"))
  BindGridView()
 End If
End Sub

Build and run the application.

Download Sample Code


3

GridView XMLDataSource Example

GridView XMLDataSource Example. In this post i'm explaining how to use XML file or XML data as XMLDataSource to populate GridView in Asp.Net 2.0,3.5,4.0.

GridView XMLDataSource Example

For this example i have created a simple xml file and added it in App_Data Folder of Asp.Net application.


The data in XML file look like shown below.



  
Amit Jain Mumbai
user 1 Delhi
User 2 Noida
User 3 Bangalore

First of All Add a GridView on aspx page and click on smart tag in design view of page and select new data source.
Browse to xml file path and click on ok.

XMLDataSource

When we click on ok we get error as displayed in the image.

XMLDataSource Error

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

This error is caused because the XML data is not in the format gridview can read.

GridView needs XML data in below mentioned format.


  
  


To fix this error we need to provide XSLT Schema. Right click on solution explorer and select add new item, from new dialog box that opens, select XSLT file.

Now we need to provide XML template in this XSLT file which should look like mentioned below.



    

    
      

HTML Source of GridView
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="XmlDataSource1">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" 
                SortExpression="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                SortExpression="Location" />
</Columns>
</asp:GridView>

<asp:XmlDataSource ID="XmlDataSource1" runat="server" 
                 DataFile="~/App_Data/XMLFile.xml" 
                 TransformFile="~/App_Data/XSLTFile.xslt">
</asp:XmlDataSource>

Build and run the application.

Download Sample Code


14

Create Rss Feeds In ASP.NET Consume With Custom Feed Reader

In this example i'm going to describe how to Create Rss Feeds In ASP.NET 2.0,3.5,4.0 And Consume With Custom Feed Reader for your web application using C# VB.Net, First of all we need to create a SQL server database to store and fetch data for feeds.

Create a database and name it RSS and create a table according to image below

And add some data in this table.


Now create a new website in Visual studio and name it RssFeed
Add a new web form and name it Employees.

Go to html source of the page
And add this page directive below the first line on the page

<%@ OutputCache Duration="120" VaryByParam="EmpId" %>


Now go to code behind of Employee page and write this code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text;
using System.Data.SqlClient;
public partial class Employees : System.Web.UI.Page
{
string strConnection =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Clear the response buffer contents
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter rssFeed = new XmlTextWriter
(Response.OutputStream, Encoding.UTF8);

//writing RSS tags
rssFeed.WriteStartDocument();
rssFeed.WriteStartElement("rss");
rssFeed.WriteAttributeString("version", "2.0");
rssFeed.WriteStartElement("channel");
rssFeed.WriteElementString("title", "Employee Details");
rssFeed.WriteElementString("link", "http://localhost:2923/RssFeed");
rssFeed.WriteElementString("description", "Details of Employees");

// create sql connection and connect to database
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Employee";
cmd.Connection = con;
con.Open();
SqlDataReader dReader ;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
rssFeed.WriteStartElement("item");
rssFeed.WriteElementString("title", dReader["FirstName"].ToString()
+ " " +dReader["LastName"].ToString());
rssFeed.WriteElementString("description", dReader["Location"].ToString());
rssFeed.WriteElementString("link",
"http://localhost:2923/RssFeed/Employees.aspx?EmpID=" +
dReader["ID"]);
rssFeed.WriteElementString("pubDate", DateTime.Now.ToString());
rssFeed.WriteEndElement();
}
dReader.Close();
con.Close();
rssFeed.WriteEndElement();
rssFeed.WriteEndElement();
rssFeed.WriteEndDocument();
rssFeed.Flush();
rssFeed.Close();
Response.End();

}

}
}

Save, build and run the project

Creating custom RSS FEED reader

Create a new project and add new web form to it , name it FeedReader.
Add a new web form and name it anything you want, go to html source of the page and add this
inside <form> tag of the form
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<table class="NormalText" runat="server"
id="tblNews" cellpadding="0" cellspacing="0">
</table>
</td>
</tr>
</table>


Now go to code behind of the page and write this code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string rss =
"http://localhost:2923/RssFeed/Employees.aspx".ToString();
try
{
FetchRssFeeds(rss);
}
catch (Exception ex)
{
}
}
public void FetchRssFeeds(string rss)
{
// Read the RSS feed
WebRequest rssRequest = WebRequest.Create(rss);
WebResponse rssResponse = rssRequest.GetResponse();

Stream rssStream = rssResponse.GetResponseStream();

// Load XML Document
XmlDocument rssDocument = new XmlDocument();
rssDocument.Load(rssStream);

XmlNodeList rssList = rssDocument.SelectNodes("rss/channel/item");

string title = "";
string link = "";
string description = "";

// Loop through RSS Feed items
for (int i = 0; i < rssList.Count; i++)
{
XmlNode rssDetail;

rssDetail = rssList.Item(i).SelectSingleNode("title");
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = "";
}

rssDetail = rssList.Item(i).SelectSingleNode("link");
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = "";
}

rssDetail = rssList.Item(i).SelectSingleNode("description");
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = "";
}

// Populate the HTML table rows and cells
HtmlTableCell cell = new HtmlTableCell();
cell.InnerHtml = "<b><a href='" + link + "' target='new'>"
+ title + "</a></b>";
HtmlTableRow trow = new HtmlTableRow();
trow.Cells.Add(cell);
tblNews.Rows.Add(trow);
HtmlTableCell cell2 = new HtmlTableCell();
cell2.InnerHtml = "<p align='justify'>" + description + "</p>";
HtmlTableRow trow2 = new HtmlTableRow();
trow2.Cells.Add(cell2);
tblNews.Rows.Add(trow2);
}
}
}


Save, build and run the project
Download the sample code




Other Posts:
C#.NET Articles -Cascading DropDownList Populate dropdown based on selection of other dropdown in ASP.NET

Install configure and troubleshooting sql server reporting services 2005

Highlight gridview row on mouse over using javascript in asp.net and C# c-sharp

Find More Articles