Friday, November 14, 2008

How To populating DropDownList control from XML data





<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="PopulateDropDwonListWithXML.aspx.cs"
Inherits="PopulateDropDwonListWithXML" %>


<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlXml" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>


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;

public partial class PopulateDropDwonListWithXML : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("DropDown.xml"));
XmlNodeList nodeList = doc.SelectNodes("//DESTINATIONS/DESTINATION");

foreach (XmlNode node in nodeList)
{
ddlXml.Items.Add(new ListItem(node.SelectSingleNode("NAME").InnerText));
}
}



}





DropDown.XML
<?xml version="1.0" encoding="utf-8" ?>

<GATEWAYS>
<GATEWAY>
<CODE>YXX</CODE>
<NAME>Abbotsford</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>

<GATEWAY>
<CODE>YKF</CODE>
<NAME>Kitchener</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>CUN</CODE>
<NAME>Cancun</NAME>
</DESTINATION>
<DESTINATION>
<CODE>X24</CODE>
<NAME>Cancun (Mayan Riviera)</NAME>
</DESTINATION>
<DESTINATION>
<CODE>POP</CODE>
<NAME>Puerto Plata</NAME>
</DESTINATION>
<DESTINATION>
<CODE>PUJ</CODE>
<NAME>Punta Cana</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
<GATEWAY>
<CODE>YQL</CODE>
<NAME>Lethbridge</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
</GATEWAYS>

How to read XML file using javascript


Supoose you have the follwing XML file . If I want to retrieve game1 moves , how would I do it using the the simplest way in javascript ?



<?xml version="1.0" encoding="utf-8" ?>
<playMoves>
<game id="game1" >
<move>
<pieceType>black</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>82</moveFrom>
<moveTo>84</moveTo>
</move>
<move>
<pieceType>white</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>87</moveFrom>
<moveTo>85</moveTo>
</move>
</game>
<game id = "game2" >
<move>
<pieceType>white</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>87</moveFrom>
<moveTo>85</moveTo>
</move>
<move>
<pieceType>black</pieceType>
<pieceName>pawn</pieceName>
<moveFrom>82</moveFrom>
<moveTo>84</moveTo>
</move>
</game>
</playMoves>




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadXMLfile.aspx.cs"
Inherits="ReadXMLfile" %>

<!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>
<script type="text/javascript">

// predeclare to prevent strict js error.
var xmlDoc;

// For IE based browsers:
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}

// For Mozilla based (standards compliant) browsers:
else if (document.implementation && document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument("","doc",null);
}

// Turn off asynchronus download.
// In other words, load the entire file before trying to do anything with it.
xmlDoc.async=false;

xmlDoc.load("Java.xml");

// Run onload of body.
function ProcessXML()
{
var game = xmlDoc.getElementsByTagName("game")[0]; // First game.
var moves = game.getElementsByTagName("move"); // All moves in game.

var results = '';

for (var i=0; moves.length > i; i++)
{
var pieceType = moves[i].getElementsByTagName("pieceType");
var pieceName = moves[i].getElementsByTagName("pieceName");
results += i+1 + '. ' + pieceType[0].firstChild.nodeValue +
' moved a ' + pieceName[0].firstChild.nodeValue + "\n\r";
}

document.getElementById("displayresults").firstChild.nodeValue = results;
}

</script>
</head>
<body onload="ProcessXML();">
<form id="form1" runat="server">
<div id="displayresults">

</div>
</form>
</body>
</html>

How To Redirect into a new window using Response.Redirect




<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="RedirectToAnotherPage.aspx.cs" Inherits="RedirectToAnotherPage" %>


<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Main Window</h1>
<asp:Button ID="btn" runat="server" Text="Redirect" OnClick="btn_Click" />
</div>
</form>
</body>
</html>


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;

public partial class RedirectToAnotherPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
public static class ResponseHelper
{

public static void Redirect(string url, string target, string windowFeatures)
{
HttpContext context = HttpContext.Current;

if ((String.IsNullOrEmpty(target) ||

target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
String.IsNullOrEmpty(windowFeatures))
{

context.Response.Redirect(url);
}
else
{
Page page = (Page)context.Handler;
if (page == null)
{
throw new InvalidOperationException(
"Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);

string script;

if (!String.IsNullOrEmpty(windowFeatures))
{
script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else
{

script = @"window.open(""{0}"", ""{1}"");";

}

script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page,

typeof(Page),

"Redirect",

script,

true);

}

}

}
protected void btn_Click(object sender, EventArgs e)
{
ResponseHelper.Redirect("popup.aspx", "_blank", "menubar=0,width=100,height=100");
}
}

Building a Simple CSV Parser in C#





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.IO;
using System.Collections.Generic;

public partial class ParseCSV : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string[]> testParse =
parseCSV("C:\\TestParse.csv");
DataTable newTable = new DataTable();
foreach (string column in testParse[0])
{
newTable.Columns.Add();
}

foreach (string[] row in testParse)
{
newTable.Rows.Add(row);
}
GridView1.DataSource = newTable;
GridView1.DataBind();
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();

using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;

while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
parsedData.Add(row);
}
}

return parsedData;
}
}


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ParseCSV.aspx.cs" Inherits="ParseCSV" %>

<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

</div>
</form>
</body>
</html>

read, write and save values in app.config file


public void ChangeConfigValue()
{
string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"web.config";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filename);
XmlNodeList nodeList = xmldoc.DocumentElement.ChildNodes;

foreach (XmlElement element in nodeList)
{
if (element.Name.ToLower() == "appsettings")
{
XmlNodeList node = element.ChildNodes;
if (node.Count > 0)
{
foreach (XmlElement el in node)
{
if (el.Attributes["key"].InnerText == "ConnectionString")
{
el.Attributes["value"].InnerText = "321";//write the value
string s= el.Attributes["value"].InnerText;//read the value
break;
}
}
}
break;
}
}
xmldoc.Save(filename);
}

How To Create TextBox Dynamically using Javascript and Read Control Value In Code Behind


Step1.Create an asp.net application with 2 Button  and a GridViewas shown below.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextboxJavascript.aspx.cs"
Inherits="DynamicTextboxJavascript" %>


<!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 id="Head1" runat="server">

<script type="text/javascript">
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = '<input type="text" name="TextBox'+num+'" value="TextBox'+num+'" >';
ni.appendChild(newdiv);
}


</script>

<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<div id="myDiv">
</div>
<input type="button" id="btnOfficial" value="Add Another TextBox" onclick="addElement();" />
<input type="hidden" value="1" id="theValue" runat="server" />
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Read" />
</form>
</body>
</html>


Step 2: Add the following code behind.



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;

public partial class DynamicTextboxJavascript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSave_Click(object sender, EventArgs e)
{

ArrayList alForm = new ArrayList();
//Because my textbox id is started
// with 2 like(TextBox2,TextBox3.....

for (int i = 2; i< Request.Form.Count - 2;i++)
{
string strId = "TextBox" + i.ToString();
string strValue = Request.Form[strId].ToString();
alForm.Add(strValue);
strValue = "";


}
//Uncomment this line and test.
//foreach (string x in Request.Form)
//{

// string strValue = Request.Form[x].ToString();
// alForm.Add(strValue);

//}
GridView1.DataSource = alForm;
GridView1.DataBind();


}
}

How To Create TextBox Control Dynamically at Runtime


In Technique when creating control dynamically in a Page Load event

handler these controls will retain their ViewState after the

PostBack, but what if controls created dynamically at runtime in a

Button Click event handler instead of Page Load event then on

PostBack these controls ViewState are lost.To persists the

ViewState of these child controls we will recreate these controls

again on a PostBack in overrideable CreateChildControls() Method

which is called whenever

ASP.NET needs to create these WebControl in a Control Tree.


// Add TextBoxes Control to Placeholder

private void CreateTextBoxes()

{

for (int counter = 0; counter <= NumberOfControls; counter++)

{

TextBox tb = new TextBox();

tb.Width = 150;

tb.Height = 18;

tb.TextMode = TextBoxMode.SingleLine;

tb.ID = "TextBoxID" + (counter + 1).ToString();

// add some dummy data to textboxes

tb.Text = "Enter Title " + counter;

phTextBoxes.Controls.Add(tb);

phTextBoxes.Controls.Add(new LiteralControl("<br/>"));

}

}

In CreateTextBoxes method I loop through ‘n’ numbers of controls that we wants to create dynamically in phTextBoxes placeholder.

// Create TextBoxes on PostBack.

protected override void CreateChildControls()

{

// Here we are recreating controls to persist the ViewState on every post back

if (Page.IsPostBack)

{

NumberOfControls += 1;

CreateTextBoxes();

}

else

{

CreateTextBoxes();

// Increase the control value to 1

NumberOfControls = 0;

}

}

CreateChildControls method, here we are recreating control on every

PostBack. If the page is created the first time we just create these

controls and save 1 in the ViewState so we know that we have created

these controls and assigned the controls id to 1.

// Increase the counter when button is clicked and add to view

state

protected void btnAddTitle_Click(object sender, EventArgs e)

{

NumberOfControls += 1;

}


In button event handler we just increase the counter by 1, and save its value to ViewState for later retrieval.
Once we have created these controls on ASP.NET page, retrieving data from these dynamically created controls is easy by using FindControl method.

// Read TextBoxes Data


private void ReadTextBoxes()

{


int n = NumberOfControls;

for (int i = 0; i <>

{


string boxName = "TextBoxID" + (i + 1).ToString();

TextBox tb = phTextBoxes.FindControl(boxName) as TextBox;


strValue += tb.Text +”\n”;



}



}

Counter