Thursday, March 10, 2011

Master-detail scenario: dropdown and griedview using xmldatasource

Hi,
I creatde an example for how to use Xpath property of the XmlDatSource to filter the records based on the dropdown selected value.
Here in the below example on page load all the records in the grid are displayed, once the user selected the employee name from the dropdown then records will be filterd based on the dropdown's selected item.
Here is the compelete Aspx page with code:

<%@ Page Language="C#" %> 
 
<%@ Import Namespace="System.Data" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<script runat="server"> 
 
    protected void ddlEmployee_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        if (ddlEmployee.SelectedItem.Text != "Select....") 
            grvDataSource.XPath = "/Employees/Employee[@Name='" + ddlEmployee.SelectedItem.Text + "']"; 
        else 
            grvDataSource.XPath = "/Employees/Employee"; 
    } 
 
</script> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title>Read XML Example</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <table> 
            <tr> 
                <td> 
                    Select Employee : 
                </td> 
                <td> 
                    <asp:DropDownList ID="ddlEmployee" runat="server" DataSourceID="ddlDataSource" DataTextField="Name" 
                        DataValueField="Id" AppendDataBoundItems="true" AutoPostBack="True" OnSelectedIndexChanged="ddlEmployee_SelectedIndexChanged"> 
                        <asp:ListItem Selected="True">Select....</asp:ListItem> 
                    </asp:DropDownList> 
                </td> 
            </tr> 
            <tr> 
                <td colspan="2"> 
                    <asp:GridView ID="grvEmployee" runat="server" DataSourceID="grvDataSource"> 
                    </asp:GridView> 
                </td> 
            </tr> 
        </table> 
    </div> 
    <asp:XmlDataSource ID="ddlDataSource" runat="server" DataFile="~/App_Data/empData.xml"> 
    </asp:XmlDataSource> 
     <asp:XmlDataSource ID="grvDataSource" runat="server" DataFile="~/App_Data/empData.xml"> 
    </asp:XmlDataSource> 
    </form> 
</body> 
</html>

empData.xml:


<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee Id="1" Name="ABC" Department="Computers" Salary="10000">
  </Employee>
  <Employee Id="2" Name="CDE" Department="Civil" Salary="20000">
  </Employee>
  <Employee Id="3" Name="FDS" Department="Computers" Salary="15000">
  </Employee>
</Employees>

No comments:

Post a Comment