Wednesday, November 26, 2008

A DetailsView Control for ASP.NET (Putting It All Together)

Putting It All Together

Let's write a page that provides a master/detail view of the Customers table in the Northwind database using a DataGrid and a DetailsView control. The page is shown in Figure 5 below.



Figure 5. A sample page to demonstrate master/details view

The following code snippet illustrates a possible handler for the UpdateCommand event fired when the user clicks to save changes made to a record. For simplicity, the handler saves only the Country field, but the mechanism shown can easily be extended to any other field.

Private Sub DetailsView1_UpdateCommand( _
ByVal sender As System.Object, _
ByVal e As Expoware.DetailsViewUpdateEventArgs) _
Handles DetailsView1.UpdateCommand
' Prepare the update statement (only field Country)
Dim cmdText As String = "UPDATE customers SET country=@country " + _
"WHERE customerid=@customerid"
Dim conn As New SqlConnection("...")
Dim cmd As New SqlCommand(cmdText, conn)
cmd.Parameters.Add("@country", e.DataItems("country"))
cmd.Parameters.Add("@customerid", e.DataItems("customerid"))

' Execute the statement
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()

' Continue update
e.NewMode = e.CurrentMode

' Reload and refresh data
BindData()
End Sub

Note the use of the DataItems collection to retrieve field values as the user edited them in the form

Move Over DataGrid, There's a New Grid in Town!

http://msdn.microsoft.com/en-us/magazine/cc163933.aspx

This article is based on the May 2004 Technology Preview of ASP.NET 2.0. All information herein is subject to change.



This article discusses:
  • The ASP.NET 2.0 GridView, FormView, and DetailsView
  • Differences between the DataGrid and the GridView
  • The programming interfaces of these controls
  • How to achieve master/detail views
This article uses the following technologies:
ASP.NET, ASP.NET 2.0, C#



Code download available at:
GridView.exe
(124 KB)
Browse the Code Online

Letter/Alphanumeric Based Paging in ASP.NET


Letter/Alphanumeric Based Paging in ASP.NET
By Joseph S. Keller
The original post is here :

http://www.codeproject.com/KB/aspnet/letterbasedpaging.aspx

Saturday, November 15, 2008

ASP.NET Site-Map Security Trimming




A common security requirement for Web sites is to allow only some members or other authenticated users to see certain pages. ASP.NET role management provides a way to restrict access to Web files based on security roles. Site-map security trimming provides a way to hide navigational links in a site map, also based on security roles. For information about role-base security, see Understanding Role Management [ http://msdn.microsoft.com/en-us/library/5k850zwb.aspx ] .


Consider the following navigational structure, which is displayed in an ASP.NET page.

Home

Products
Hardware
Software
Discounts
Services
Training
Consulting
Support


Clients who are not members of a role called Customers are restricted from viewing the Support Web page by an ASP.NET access rule that is configured for the Support.aspx page.


To hide the Support link in the navigational display, configure the site-map provider in the Web.config file to enable security trimming. No additional changes are needed because the application will use ASP.NET URL authorization and file authorization to hide the link to the Support page. The XmlSiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.xmlsitemapprovider.aspx ] control that is included with ASP.NET version 2.0 automatically performs authorization checks against each site-map node by using the URL- and file-authorization features.



If you want show the Support link to clients who are not in the Customers role, you can use the roles attribute in the site-map node for the Support.aspx file. The roles attribute expands access to a site-map node beyond the level of access that URL authorization and file authorization grant.


The following code example sets the roles attribute for the Support page to Customers. After enabling security trimming, this setting allows users in the Customers role to view the navigation link to the Support page, even if they are not permitted to view the actual file by URL authorization or file authorization.

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


<siteMap>
<!-- other <siteMapNode> elements -->
<siteMapNode title="Support" description="Support"
url="~/Customers/Support.aspx" roles="Customers" />
</siteMap>

Users who are not members of the Customers role would see the following navigational structure if they are restricted from viewing the Support page because of URL- or file-authorization rules.

Home

Products
Hardware
Software
Discounts
Services
Training
Consulting

Enabling Security Trimming


Security trimming works in conjunction with ASP.NET roles. Therefore, pages must be restricted by using access rules (allow and deny elements) for security trimming to work. For more information about access rules, see Managing Authorization Using Roles [ http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx ] .


Security trimming is not enabled by default, and it cannot be enabled programmatically; it can only be set in the Web.config file. This is also true for any custom class that inherits from the SiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.sitemapprovider.aspx ] class.


To enable security trimming, you need to configure a siteMap Element (ASP.NET Settings Schema) [ http://msdn.microsoft.com/en-us/library/1e333zt4.aspx ] element in your Web.config file. If your site map uses the default ASP.NET site-map provider, then the Web.config file might not contain a siteMap Element (ASP.NET Settings Schema) [ http://msdn.microsoft.com/en-us/library/1e333zt4.aspx ] element, in which case you will need to add one. The following code example adds the default site-map provider and enables security trimming.

<system.web>


<!-- …other configuration settings -->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider"
description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider "
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>

</system.web>




The security-trimming feature uses URL authorization on each request to determine whether a user has access to a URL that is associated with a siteMapNode element. This extra work reduces performance depending on the number of nodes that are being authorized. When security trimming is enabled, you can use the following methods to improve performance:



  • Limit the number of nodes in the site-map file Site-map files with more than 150 nodes can take substantially longer to perform security-trimming operations.


  • Set the roles attribute explicitly on siteMapNode elements Note that setting the roles attribute to a wildcard character, or asterisk (*), should be used only for nodes that can safely be displayed to any client. The presence of a roles attribute allows ASP.NET to bypass URL authorization for the URL that is associated with the siteMapNode when a user belongs to one of the roles that is listed in the attribute.




To prevent the unintended trimming of child site-map nodes, configure authorization rules and roles attributes carefully. Consider the following navigational structure, which is displayed in an ASP.NET page.

Home

Products
Hardware


The URL- or file-authorization rules set on the Products.aspx file should not be more restrictive than the authorization rules that are set on the Hardware.aspx file. Otherwise, the Hardware link will be hidden from users who should be able to view it because the parent link to Products will be hidden. To expose the hidden links, add to both site-map nodes a roles attribute that lists the neglected ASP.NET roles.



It is recommended that the root node in a site map allow everyone access. To do this, set the roles attribute to an asterisk (*), or wildcard character, as shown in the following code example.

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

<siteMap>
<siteMapNode title="Home" description="Home"
url="default.aspx" roles="*">
<!-- other <siteMapNode> elements -->

</siteMapNode>
</siteMap>


In a site map, you can reference URLs that are outside of your Web application. Access to a URL outside of the application cannot be tested by ASP.NET. Therefore, if you enable security trimming, the site-map node will not be visible unless you set the roles attribute to an asterisk (*), which enables all clients to view the site-map node without first testing access to the URL.



You can use multiple site maps together to define the navigation structure for a single Web site. For example, a Web.sitemap file is similar to a Web.config file because it can be split up and placed in different folders.


Site maps are linked to each other by referencing a child site-map file or provider in the siteMapFile or provider attribute of a SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] object in the parent site map.



The following code example illustrates a site-map node that references another site map.

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

<siteMap>

<!-- other <siteMapNode> elements -->
<siteMapNode siteMapFile="~/Customers/Customers.sitemap"
securityTrimmingEnabled="true" />

</siteMap>





You can use navigation controls to add site navigation to your pages with little or no code, but you can also work with site navigation programmatically. When your Web application runs, ASP.NET exposes a SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object that reflects the site-map structure. All of the members of the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object are static. The SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object, in turn, exposes a collection of SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects that contain properties for each node in the map. This is because, when you use the SiteMapPath [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemappath.aspx ] control, the control works with the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] and SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects to render the appropriate links automatically.



You can use the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] , SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] , and SiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.sitemapprovider.aspx ] objects in your own code to traverse the site-map structure or create a custom control to display site-map data. You cannot write to the site map, but you can alter site-map nodes in the instance of the object. For more information, see How to: Programmatically Modify Site-Map Nodes in Memory [ http://msdn.microsoft.com/en-us/library/ms178425.aspx ] or How to: Programmatically Enumerate Site-Map Nodes [ http://msdn.microsoft.com/en-us/library/ms178424.aspx ] .



ASP.NET uses the default site-map provider, XmlSiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.xmlsitemapprovider.aspx ] , to read the Web.sitemap file. If you want to store site-map information in a location other than the site-map file, you can create your own site-map provider and configure your application to call the custom provider. The site-map provider is configured in the Web.config file. When the application runs, ASP.NET will invoke your provider, which can retrieve site-map information as needed. ASP.NET then creates and populates the SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects based on the information that your provider returns. These objects can be programmatically accessed by using the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] class. For more information, see Implementing ASP.NET Site-Map Providers [ http://msdn.microsoft.com/en-us/library/ms178431.aspx ] .

ms178428.alert_security(en-us,VS.90).gifSecurity Note:



Implementing a custom site-map provider that stores site-map data in a file with a file name extension other than .sitemap is a potential security risk. By default, ASP.NET is configured to protect files with known file name extensions — such as .sitemap — from being downloaded by a client. To help protect your data, place any custom site-map data files that have a file name extension other than .sitemap in the App_Data folder. For more information, see

Securing ASP.NET Site Navigation [ http://msdn.microsoft.com/en-us/library/ms227425.aspx ] .


When enabled, security trimming affects the behavior of some of the members in the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] , SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] , and SiteMapNodeCollection [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnodecollection.aspx ] classes. When using these classes, you will see the following behavior:



  • A null is returned by a site navigation API member if it attempts to reference a site-map node that the user does not have the security rights to see. For example, the CurrentNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.currentnode.aspx ] , NextSibling [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.nextsibling.aspx ] , ParentNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.parentnode.aspx ] , and PreviousSibling [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.previoussibling.aspx ] properties will return a null if the properties attempt to return a site-map node that is restricted.



  • If a site navigation API member needs to traverse the tree of site-map nodes, any site-map node that the user is not allowed to see is excluded from the traversal. For example, when the ChildNodes [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.childnodes.aspx ] method runs, the collection of nodes is filtered to include only those nodes that the user is allowed to see. In the case of API members that need to keep track of node paths, such as the Clone [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.clone.aspx ] or IsDescendantOf [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.isdescendantof.aspx ] methods, the paths end at restricted nodes. This can result in cloning operations returning a reduced number of nodes. It can also result in the IsDescendantOf [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.isdescendantof.aspx ] method returning a value of false even though structurally a node might actually be a descendant of the requested node.



  • An InvalidOperationException [ http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx ] exception is returned if a site navigation API member references a root node that the user does not have the security rights to see. Only the root node of the root provider needs to be accessible to all users, which prevents an exception from being thrown when first obtaining the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object.


  • A ConfigurationException [ http://msdn.microsoft.com/en-us/library/system.configuration.configurationexception.aspx ] exception is thrown if a SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] object references another site-map file or provider incorrectly.

ms178428.alert_note(en-us,VS.90).gifNote:



In a site map, you can reference URLs that are outside of your Web application. Access to a URL outside of the application cannot be tested by ASP.NET. Therefore, if you enable security trimming, the site-map node will not be visible unless you set the roles attribute to an asterisk (*), which enables all clients to view the site-map node without first testing access to the URL.

Tasks

Walkthrough: Filtering Site-Map Nodes Based on Security Roles [ http://msdn.microsoft.com/en-us/library/ms178429.aspx ]

Concepts

Securing ASP.NET Site Navigation [ http://msdn.microsoft.com/en-us/library/ms227425.aspx ]
Securing Data Access [ http://msdn.microsoft.com/en-us/library/ms178375.aspx ]

Other Resources

Managing Authorization Using Roles [ http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx ]
ASP.NET Application Security in Hosted Environments [ http://msdn.microsoft.com/en-us/library/ssd9kbbc.aspx ]


Tags:














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