Tuesday, February 3, 2009

ASP.NET 2.0 text field value is not being passed to code behind

Whenever ASP.NET 2.0 TextBox component is set to Disabled or ReadOnly through the VS2005 designer, and then modified by client JavaScript - input value is not being persisted on the postback.
To work around this - set Disabled or ReadOnly from the client JavaScript when the page loads.
e.g.

function ExecuteOnLoad()
{
document.getElementById("txtInput").readOnly = true;
document.getElementById("txtOutput").disabled = true;
}

Viewstate is lost for dynamically (javascript/AJAX) generated dropdown box

I had a page with the dynamically (AJAX) populated dropdown box, which was failing to persist the state whenever ASP.NET postback was executed. To work around the problem - I created a hidden field, and attached SelectedIndexChange event to the dropdown, which populated hidden field with the selected value from the dropdown...
Simple enough!

Just make sure EnableEventValidation is set to false, otherwise the following error is being thrown:

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Pass DataSet into XML C#

Here's a simple code of retrieving data from a Database into XML Document:


using System.Xml;
using System.Configuration;
using System.Data.SqlClient;

protected XmlDocument GetXML(int input)
{
const string strStoredProc = "SP";
const string ROOTNODE = "ROOT";
const string NODENAME = "NODE";
string sqlConnectionString = GetConnectionString();
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
SqlCommand sqlCommand;
XmlDataDocument xmlDoc = null;
try
{
sqlCommand = new SqlCommand(strStoredProc, sqlConnection);


sqlCommand.CommandType = CommandType.StoredProcedure;

sqlCommand.Parameters.Add("@INPUT", SqlDbType.Int);
sqlCommand.Parameters["@IN_Year"].Value = Int32.Parse(input);

sqlConnection.Open();

DataSet ds = new DataSet();
ds.DataSetName = ROOTNODE;

ds.Load(sqlCommand.ExecuteReader(), LoadOption.OverwriteChanges, NODENAME);
xmlDoc = new XmlDataDocument(ds);
}
catch (Exception ex)
{

}
finally
{
sqlConnection.Dispose();
}
return xmlDoc;

}