Monday, May 9, 2011

Show XML file in webpage in Tree Stucture

Step 1: Create test.xml


<?xml version="1.0"?>
<?xml-stylesheet href="catalog.xsl" type="text/xsl"?>
<catalog>
  <product description="Cardigan Sweater" product_image="cardigan.jpg">
    <catalog_item gender="Men's">
      <item_number>QWZ5671</item_number>
      <price>39.95</price>
      <size description="Medium">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
      </size>
      <size description="Large">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
      </size>
    </catalog_item>
    <catalog_item gender="Women's">
      <item_number>RRX9856</item_number>
      <price>42.50</price>
      <size description="Small">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
      </size>
      <size description="Medium">
        <color_swatch image="red_cardigan.jpg">Red</color_swatch>
        <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
        <color_swatch image="black_cardigan.jpg">Black</color_swatch>
      </size>
      <size description="Large">
        <color_swatch image="navy_cardigan.jpg">Navy</color_swatch>
        <color_swatch image="black_cardigan.jpg">Black</color_swatch>
      </size>
      <size description="Extra Large">
        <color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
        <color_swatch image="black_cardigan.jpg">Black</color_swatch>
      </size>
    </catalog_item>
  </product>
</catalog>


Step 2: Create XMLDisplay.css


@charset "utf-8";
/* CSS Document */
.Utility {
color: black;
}
.NodeName {
font-weight:bold;
color: #800080;
font-family: tahoma;
font-size: 11px;
}
.AttributeName
{
font-weight:bold;
color: black;
font-family: tahoma;
font-size: 11px;
}
.AttributeValue
{
color:blue;
font-family: tahoma;
font-size: 11px;
}
.NodeValue
{
color: black;
font-family: tahoma;
font-size: 11px;
}
.Element {
border-left-color:Black;
border-left-width:thin;
border-left-style:dotted;
padding-top:0px;
margin-top:10px;
}
.Clickable {
font-weight:900;
font-size:large;
color: #800080;
cursor:pointer;

vertical-align:middle;
}


Step 3: Create XMLDisplay.js


function LoadXML(ParentElementID,URL)
{
var xmlHolderElement = GetParentElement(ParentElementID);
if (xmlHolderElement==null) { return false; }
ToggleElementVisibility(xmlHolderElement);
return RequestURL(URL,URLReceiveCallback,ParentElementID);
}
function LoadXMLDom(ParentElementID,xmlDoc)
{
if (xmlDoc) {
var xmlHolderElement = GetParentElement(ParentElementID);
if (xmlHolderElement==null) { return false; }
while (xmlHolderElement.childNodes.length) { xmlHolderElement.removeChild(xmlHolderElement.childNodes.item(xmlHolderElement.childNodes.length-1)); }
var Result = ShowXML(xmlHolderElement,xmlDoc.documentElement,0);

var ReferenceElement = document.createElement('div');
var Link = document.createElement('a');
//Link.setAttribute('href','http://www.levmuchnik.net/Content/ProgrammingTips/WEB/XMLDisplay/DisplayXMLFileWithJavascript.html');
//var TextNode = document.createTextNode('Source: Lev Muchnik');
Link.appendChild(TextNode);

xmlHolderElement.appendChild(Link);
return Result;
}
else { return false; }
}
function LoadXMLString(ParentElementID,XMLString)
{
xmlDoc = CreateXMLDOM(XMLString);
return LoadXMLDom(ParentElementID,xmlDoc) ;
}
////////////////////////////////////////////////////////////
// HELPER FUNCTIONS - SHOULD NOT BE DIRECTLY CALLED BY USERS
////////////////////////////////////////////////////////////
function GetParentElement(ParentElementID)
{
if (typeof(ParentElementID)=='string') { return document.getElementById(ParentElementID); }
else if (typeof(ParentElementID)=='object') { return ParentElementID;}
else { return null; }
}
function URLReceiveCallback(httpRequest,xmlHolderElement)
{
 try {
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200) {
var xmlDoc = httpRequest.responseXML;
if (xmlHolderElement && xmlHolderElement!=null) {
xmlHolderElement.innerHTML = '';
return LoadXMLDom(xmlHolderElement,xmlDoc);
}
                } else {
                    return false;
                }
            }
        }
        catch( e ) {
            return false;
        }
}
function RequestURL(url,callback,ExtraData) { // based on: http://developer.mozilla.org/en/docs/AJAX:Getting_Started
        var httpRequest;
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) { httpRequest.overrideMimeType('text/xml'); }
        }
        else if (window.ActiveXObject) { // IE
            try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP");   }
            catch (e) {
  try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) {}
            }
        }
        if (!httpRequest) { return false;   }
        httpRequest.onreadystatechange = function() { callback(httpRequest,ExtraData); };
        httpRequest.open('GET', url, true);
        httpRequest.send('');
return true;
    }
function CreateXMLDOM(XMLStr)
{
if (window.ActiveXObject)
{
 xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 xmlDoc.loadXML(XMLStr);
 return xmlDoc;
}
else if (document.implementation && document.implementation.createDocument)  {
 var parser=new DOMParser();
 return parser.parseFromString(XMLStr,"text/xml");
}
else {
return null;
}
}

var IDCounter = 1;
var NestingIndent = 15;
function ShowXML(xmlHolderElement,RootNode,indent)
{
if (RootNode==null || xmlHolderElement==null) { return false; }
var Result  = true;
var TagEmptyElement = document.createElement('div');
TagEmptyElement.className = 'Element';
TagEmptyElement.style.position = 'relative';
TagEmptyElement.style.left = NestingIndent+'px';
if (RootNode.childNodes.length==0) {
    var ClickableElement = AddTextNode(TagEmptyElement,'','Clickable') ;
    ClickableElement.id = 'div_empty_' + IDCounter;
    AddTextNode(TagEmptyElement,'<','Utility') ;
    AddTextNode(TagEmptyElement,RootNode.nodeName ,'NodeName')
    for (var i = 0; RootNode.attributes && i < RootNode.attributes.length; ++i) {
      CurrentAttribute  = RootNode.attributes.item(i);
      AddTextNode(TagEmptyElement,' ' + CurrentAttribute.nodeName ,'AttributeName') ;
      AddTextNode(TagEmptyElement,'=','Utility') ;
      AddTextNode(TagEmptyElement,'"' + CurrentAttribute.nodeValue + '"','AttributeValue') ;
    }
    AddTextNode(TagEmptyElement,' />') ;
    xmlHolderElement.appendChild(TagEmptyElement);
    //SetVisibility(TagEmptyElement,true);  
}
else { // mo child nodes
   
    var ClickableElement = AddTextNode(TagEmptyElement,'+','Clickable') ;
    ClickableElement.onclick  = function() {ToggleElementVisibility(this); }
    ClickableElement.id = 'div_empty_' + IDCounter;

    AddTextNode(TagEmptyElement,'<','Utility') ;
    AddTextNode(TagEmptyElement,RootNode.nodeName ,'NodeName')
    for (var i = 0; RootNode.attributes && i < RootNode.attributes.length; ++i) {
      CurrentAttribute  = RootNode.attributes.item(i);
      AddTextNode(TagEmptyElement,' ' + CurrentAttribute.nodeName ,'AttributeName') ;
      AddTextNode(TagEmptyElement,'=','Utility') ;
      AddTextNode(TagEmptyElement,'"' + CurrentAttribute.nodeValue + '"','AttributeValue') ;
    }

    AddTextNode(TagEmptyElement,'>  </','Utility') ;
    AddTextNode(TagEmptyElement,RootNode.nodeName,'NodeName') ;
    AddTextNode(TagEmptyElement,'>','Utility') ;
    xmlHolderElement.appendChild(TagEmptyElement);
    SetVisibility(TagEmptyElement,false);
    //----------------------------------------------
   
    var TagElement = document.createElement('div');
    TagElement.className = 'Element';
    TagElement.style.position = 'relative';
    TagElement.style.left = NestingIndent+'px';
    ClickableElement = AddTextNode(TagElement,'-','Clickable') ;
    ClickableElement.onclick  = function() {ToggleElementVisibility(this); }
    ClickableElement.id = 'div_content_' + IDCounter;
    ++IDCounter;
    AddTextNode(TagElement,'<','Utility') ;
    AddTextNode(TagElement,RootNode.nodeName ,'NodeName') ;
   
    for (var i = 0; RootNode.attributes && i < RootNode.attributes.length; ++i) {
        CurrentAttribute  = RootNode.attributes.item(i);
        AddTextNode(TagElement,' ' + CurrentAttribute.nodeName ,'AttributeName') ;
        AddTextNode(TagElement,'=','Utility') ;
        AddTextNode(TagElement,'"' + CurrentAttribute.nodeValue + '"','AttributeValue') ;
    }
    AddTextNode(TagElement,'>','Utility') ;
    TagElement.appendChild(document.createElement('br'));
    var NodeContent = null;
    for (var i = 0; RootNode.childNodes && i < RootNode.childNodes.length; ++i) {
      if (RootNode.childNodes.item(i).nodeName != '#text') {
        Result &= ShowXML(TagElement,RootNode.childNodes.item(i),indent+1);
      }
      else {
        NodeContent =RootNode.childNodes.item(i).nodeValue;
      }
    }
    if (RootNode.nodeValue) {
      NodeContent = RootNode.nodeValue;
    }
    if (NodeContent) {
      var ContentElement = document.createElement('div');
      ContentElement.style.position = 'relative';
      ContentElement.style.left = NestingIndent+'px';
      AddTextNode(ContentElement,NodeContent ,'NodeValue') ;
      TagElement.appendChild(ContentElement);
    }
    AddTextNode(TagElement,'  </','Utility') ;
    AddTextNode(TagElement,RootNode.nodeName,'NodeName') ;
    AddTextNode(TagElement,'>','Utility') ;
    xmlHolderElement.appendChild(TagElement);
  }

// if (indent==0) { ToggleElementVisibility(TagElement.childNodes(0)); } - uncomment to collapse the external element
return Result;
}
function AddTextNode(ParentNode,Text,Class)
{
NewNode = document.createElement('span');
if (Class) {  NewNode.className  = Class;}
if (Text) { NewNode.appendChild(document.createTextNode(Text)); }
if (ParentNode) { ParentNode.appendChild(NewNode); }
return NewNode;
}
function CompatibleGetElementByID(id)
{
if (!id) { return null; }
if (document.getElementById) { // DOM3 = IE5, NS6
return document.getElementById(id);
}
else {
if (document.layers) { // Netscape 4
return document.id;
}
else { // IE 4
return document.all.id;
}
}
}
function SetVisibility(HTMLElement,Visible)
{
if (!HTMLElement) { return; }
var VisibilityStr  = (Visible) ? 'block' : 'none';
if (document.getElementById) { // DOM3 = IE5, NS6
HTMLElement.style.display =VisibilityStr;
}
else {
if (document.layers) { // Netscape 4
HTMLElement.display = VisibilityStr;
}
else { // IE 4
HTMLElement.id.style.display = VisibilityStr;
}
}
}
function ToggleElementVisibility(Element)
{
if (!Element|| !Element.id) { return; }
try {
ElementType = Element.id.slice(0,Element.id.lastIndexOf('_')+1);
ElementID = parseInt(Element.id.slice(Element.id.lastIndexOf('_')+1));
}
catch(e) { return ; }
var ElementToHide = null;
var ElementToShow= null;
if (ElementType=='div_content_') {
ElementToHide = 'div_content_' + ElementID;
ElementToShow = 'div_empty_' + ElementID;
}
else if (ElementType=='div_empty_') {
ElementToShow= 'div_content_' + ElementID;
ElementToHide  = 'div_empty_' + ElementID;
}
ElementToHide = CompatibleGetElementByID(ElementToHide);
ElementToShow = CompatibleGetElementByID(ElementToShow);
if (ElementToHide) { ElementToHide = ElementToHide.parentNode;}
if (ElementToShow) { ElementToShow = ElementToShow.parentNode;}
SetVisibility(ElementToHide,false);
SetVisibility(ElementToShow,true);
}

Step 4: Create ShowXML.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowXML.aspx.cs" Inherits="CollapsiblePanel.ShowXML" %>

<!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>Untitled Page</title>
    <link href="XMLDisplay.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="XMLDisplay.js"> </script>
</head>
<body>
    <form id="form1" runat="server">
<div id="XMLHolder" style="background-color:#FFFFFF;" class="Element" >  </div>
<script type="text/javascript">LoadXML('XMLHolder','walkthru.xml'); </script>
    </form>
 
</body>
</html>




Thursday, February 3, 2011

Get Primary key value in gridview on edit command


Step 1: Create a form and put div that contain questionid and question description style="Display:none", to get question id.


Step 2: Put the following code on rowcommand of gridview

protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("edits"))
            {
                int index = Convert.ToInt32(e.CommandArgument.ToString());
                int ServerID = Convert.ToInt32(GridView1.DataKeys[index].Value);
                TxtQuestionId.Text = ServerID.ToString();

                SqlConnection mycon = new SqlConnection(connectionstring);
                SqlCommand mycmd = new SqlCommand("select * from QuestionMaster where                                                             QuestionId='"+TxtQuestionId.Text+"'", mycon);
                mycon.Open();
                SqlDataAdapter myadpt = new SqlDataAdapter(mycmd);
                DataSet ds = new DataSet();
                myadpt.Fill(ds);
                ddCourse.SelectedValue = ds.Tables[0].Rows[0]["CourseId"].ToString();
                ddTopic.SelectedValue = ds.Tables[0].Rows[0]["TopicId"].ToString();
                TxtQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
      }
//To hide particular cell from Grid View 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[1].Visible = false;
        }



Step 3: And at last put the following code on submit button click

 protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection mycon = new SqlConnection(connectionstring);
            SqlCommand mycmd = new SqlCommand("UpdateQuestionMaster", mycon);
            mycmd.CommandType = CommandType.StoredProcedure;
            mycmd.Parameters.Add("@CourseId", SqlDbType.Int).Value = ddCourse.SelectedValue;
            mycmd.Parameters.Add("@TopicId", SqlDbType.Int).Value = ddTopic.SelectedValue;
            mycmd.Parameters.Add("@Questiondescription", SqlDbType.NVarChar).Value = TxtQuestionDes.Text;
            mycmd.Parameters.Add("@Question", SqlDbType.NVarChar).Value = TxtQuestion.Text;
            mycmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = TxtQuestionId.Text;
            mycon.Open();
            mycmd.ExecuteNonQuery();
        }


Also see my other blogs: Reset Table id to zero in sql server
                                                               Tree View using database