Sohel’s Blog

November 18, 2008

An important issue while using Master page: ID changed of the Controls(Multiple controls)

Filed under: Asp.Net — sohel02 @ 12:20 am

In my previous post “An important issue while using Master page: ID changed of the Controls” I have explained what problem a developer can face while using Master Page and JavaScript together. I have discussed the problem and shown a way to the solution.

I have used only one control to keep the example simple.

Recently some of my blog readers have asked me about how they can use multiple controls while adding JavaScript at server side along with Master Pages. Well guys, today I will explain the process of using multiple controls by an example. So let’s start!!!

The first step is similar to my previous post. Create a new website in VS2005 and add a Master Page in it. Name the master page as “Site.master”.  Change the ID of contentplaceholder to CPH. Now switch the VS 2005 to source view and you will probably see the following code;

<%@ Master Language=”C#” AutoEventWireup=”true” CodeFile=”MasterPage.master.cs” Inherits=”MasterPage” %><!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:contentplaceholder id=”CPH” runat=”server”>
</asp:contentplaceholder>
</div>
</form>
</body>
</html>

Now add a new page to your website (Default.aspx) and select “Site.master” as it’s master page. Now add two textboxes in your “Default.aspx” page. Change the IDs of the textboxes to “txtName” and “txtAge” respectively.Add a button control to the page “Default.aspx” and change its ID to “btnShow”. Change the button text to “show”. Your code will look like the following;

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default3.aspx.cs” Inherits=”Default3″ Title=”Untitled Page” %><asp:Content ID=”Content1″ ContentPlaceHolderID=”CPH” Runat=”Server”>

<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
<asp:TextBox ID=”txtAge” runat=”server”></asp:TextBox>
<asp:Button ID=”btnShow” runat=”server” Text=”Show ” OnClientClick=”IDIssue();”/>

</asp:Content>

Now add the following code segment in the in Page_Load event of Deafault.aspx.cs file.

ContentPlaceHolder cp = (ContentPlaceHolder)Page.Master.FindControl(“CPH”);
TextBox tbName = (TextBox)cp.FindControl(“txtName”);
TextBox tbAge = (TextBox)cp.FindControl(“txtAge”);
string script=string.Format(@”function IDIssue()
{{ var txtName=document.getElementById(‘{0}’);
var txtAge=document.getElementById(‘{1}’);
alert(‘your name is ‘+ txtName.value+’ and age is ‘+txtAge.value); }}”,tbName.ClientID, tbAge.ClientID);
ClientScript.RegisterClientScriptBlock(this.GetType(), “IDIssue”, script, true);

If you run the website from VS2005 you will see two Textboxes on the page. If you enter your name on the first textbox and age in the second textbox, then click th show button, an JavaScript alert box will display a message containing your name and age. That’s it.

For three controls, you have to use following code segment in the Page_Load event replacing the “string script=string.format(…..);” section;

string script=string.Format(@”function IDIssue()
{{ var ctrl1=document.getElementById(‘{0}’);
var ctrl2=document.getElementById(‘{1}’);
var ctrl3=document.getElementById(‘{2}’);
// add necessary implemenation here
}}”, ctrl1.ClientID, ctrl2.ClientID, ctrl3.ClientID);

We are assuming that we have three controls name ctrl1, ctrl2 and ctrl3.

Now, you may have thought what if we have more than three controls??

Well, if you notice the methods overloaded for string.Format(), you will see that there is method which accepts an array as arguments.

string string.Format(string format, params object[] args);

If you have to format a string which has more than three arguments, you can use the above function. Obviously, you can also use it for less than three arguments. If we have some controls such as ctrl1,ctrl2,ctrl3 ctr4 etc.  then, the syntax is;

string[] paramsStr=new string[4];
paramsStr[0]=ctrl1.ClientID;
paramsStr[1]=ctrl2.ClientID;
paramsStr[2]=ctrl3.ClientID;
paramsStr[3]=ctrl4.ClientID;string script=string.Format(@”function IDIssue()
{{ var ctrl1=document.getElementById(‘{0}’);
var ctrl2=document.getElementById(‘{1}’);
var ctrl3=document.getElementById(‘{2}’);
var ctrl4=document.getElementById(‘{3}’);
// add necessary implemenation here
}}”, paramsStr)

Hope this will work!!!

July 2, 2008

How to use DataReader in C#.Net

Filed under: C#.Net — sohel02 @ 4:47 pm

DataReader works like a cursor to the table mentioned in the select statement. When read() method is called for the first time, it points to the first row of the record set. If the read() method is called again, then it points to 2nd row and so on. However, once you have passed through a row, you can not get back. Because, DataReader is a cursor of forward only type. So, it is not possible to traverse back. DataReader has HasRows property by which you can check whether a result set exists or not.

You should always remember the following points while accessing data.

  • Data connections are valuable resources. So always try to connect late and release early.
  • Always put the data access code segments into try-catch block. In general, you can not open two Datareader at the same time in the same scope.
  • So, make sure you have closed the DataReader while your works have done. Then open the other.

The following code segment uses DataReader to fill a Combobox with the country name.

// Instantiate a OleDb connection object
OleDbConnection connection = new OleDbConnection();

//assign the proper connection string(here we have an access database) to the connection
connection.ConnectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Test.mdb”;

// Instantiate a OleDb command object
OleDbCommand command = new OleDbCommand();

//assign the command to be executed
command.CommandText = “Select CountryID,CountryName from tblCountry”;

//bind the command object to the connection
command.Connection = connection;

try
{
// opening the connection
connection.Open();
OleDbDataReader dr = command.ExecuteReader();

if (dr.HasRows)
{
// Iterate through the table
while (dr.Read())
{
//adding item to the combobox. you can also use dr[1] to get the country name
comboBox1.Items.Add(dr["CountryName"]);
}
}

}
catch (Exception ex)
{
MessageBox.Show(“The following error occured :\r\n” + ex.ToString());
}
finally
{
// close the connection and DataReader
connection.Close();
dr.Close();
}
}

DataReader is most useful in the scenario where the data is required only once and read only format. That is if you are not going to make any changes, just using the data for menu or combobox or another selection menu that requires loading only once; then you can choose DataReader.

How to add html control dynamically using JavaScript (DOM)

Filed under: JavaScript — sohel02 @ 2:53 pm
Tags: , , ,

Last few days I was so busy with my work that I have not enough time to write. I am afraid this article may not enough descriptive. Still, it may be useful.

JavaScript is a very useful language for client side scripting. Often you need to add control dynamically in your page. Sometimes you need customization according to client selection criteria. JavaScript is very handy to fulfill these. There are many ways to add a control dynamically using JavaScript. I would suggest the DOM architecture. Now what is DOM? DOM (document Object Model) is a platform- and language-independent standard that can be used for Dynamic HTML. Using DOM you can traverse both way, parent to child or child to parent. It is also useful for modifying the style sheets. The following code shows how to add a textbox dynamically using JavaScript. Just open a notepad copy and paste the following code, save it as HTML. Then Open it in a browser.

<!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>
<title>Untitled Page</title>

<script language=”javascript” type=”text/javascript”>
<!–

var NumOfRow=1;

function Button1_onclick()
{
NumOfRow++;

// get the refference of the main Div
var mainDiv=document.getElementById(‘MainDiv’);

// create new div that will work as a container
var newDiv=document.createElement(‘div’);
newDiv.setAttribute(‘id’,'innerDiv’+NumOfRow);

//create span to contain the text
var newSpan=document.createElement(’span’);
newSpan.innerHTML=”Enter Your Mail Address “;

// create new textbox for email entry
var newTextBox=document.createElement(‘input’);
newTextBox.type=’text’;
newTextBox.setAttribute(‘id’,'txtAddr’+NumOfRow);

// create remove button for each email adress

var newButton=document.createElement(‘input’);
newButton.type=’button’;
newButton.value=’Remove’;
newButton.id=’btn’+NumOfRow;

// atach event for remove button click
newButton.onclick=function RemoveEntry() { var mainDiv=document.getElementById(‘MainDiv’);
mainDiv.removeChild(this.parentNode);
}

// append the span, textbox and the button
newDiv.appendChild(newSpan);
newDiv.appendChild(newTextBox);
newDiv.appendChild(newButton);

// finally append the new div to the main div
mainDiv.appendChild(newDiv);

}
// –>
</script>

</head>

<body>
<div id=”MainDiv”>
Enter Your Mail Address <input id=”txtAddr1″ type=”text” />
<input id=”Button1″ type=”button” value=”Add More” onclick=”Button1_onclick()” /></div>
</body>
</html>

Here in our web page we have a simple form which includes a div Named “MainDiv”. Inside the div a textbox and a button is included. When you click the button new textbox with a remove button appears. If you click again, another pair is added and so on……

June 14, 2008

How to add JavaScript at runtime using C# in Asp.Net 2.0

Filed under: Asp.Net — sohel02 @ 3:09 am

Asp. Net 2.0 provides lots of feature that are very exciting and cool. When developing a site, you must need JavaScript at some stage. You can add your script using several ways. You can place your script along with your control, in the <script></script> block or in a separate .js file and link it. However, Asp.Net 2.0 is giving more options to you !!! You can place your JavaScript Code using C#.

Asp.Net 2.0  provides three method to accomplish this. They are;

  • Page.ClientScript.RegisterClientScriptBlock
  • Page.ClientScript.RegisterStartupScript
  • Page.ClientScript.RegisterClientScriptInclude

Using Page.ClientScript.RegisterClientScriptBlock: If you want to place your JavaScript code at the top of your page use this method. Add a new page to your site. Put a textbox and a button in your page. Your page should show the following code segment when source view is selected in VS2005;

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!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:TextBox ID=”txtName” runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” Text=”Show” OnClientClick=”ShowName()”/></div>
</form>
</body>
</html>

Now go to the corresponding .cs file and add the following code segment in the Page_Load Event.

string Script=@”function ShowName() { var txt=document.getElementById(‘txtName’); alert(‘Your name is: ‘+txt.value); }”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “ShowName”, Script, true);

Now run the page, write your name in the text box and click on the show button.  A alert box will apear showing the name you entered in the textbox. If you see the source of the page from the browser, you will see;

<!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><title>
Untitled Page
</title></head>
<body>
<form name=”form1″ method=”post” action=”Default.aspx” id=”form1″>
<div>
<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTkwNjc4NTIwMWRkTzm0n/ZgrBCe8mqHt/E13Ywr550=” />
</div>

<script type=”text/javascript”>
<!–
function ShowName() { var txt=document.getElementById(‘txtName’); alert(‘Your name is: ‘+txt.value); }// –>
</script>

<div>
<input name=”txtName” type=”text” value=”dfdf” id=”txtName” />
<input type=”submit” name=”Button1″ value=”Show” onclick=”ShowName();” id=”Button1″ /></div>

<div>

<input type=”hidden” name=”__EVENTVALIDATION” id=”__EVENTVALIDATION” value=”/wEWAwLSpcn1CALEhISFCwKM54rGBm5dD6y7hGrJEo26L3AW0W0IM8hA” />
</div></form>
</body>
</html>

You see !!! The JavaScript has been added to your page. In this way you can place your Script at run time. Of course, there are two other way. I will discuss them in my future post.

June 12, 2008

An important issue while using Master page: ID changed of the Controls

Master page is an excellent feature provided in Asp.Net version 2.0. It is a common practice to give the user same look and feel across your site. Master page is a very handy feature to accomplish this. I will discuss an issue that must be in your knowledge while designing your site.

Those who are familiar with Master Page know that it works like a container. It actually contains the content page. Add a Master page in your site and name it Site.master.  Change the ID of contentplaceholder to CPH . Now switch the VS 2005 to source view and  you will see the following code.

<%@ Master Language=”C#” AutoEventWireup=”true” CodeFile=”Site.master.cs” Inherits=”Site” %><!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:contentplaceholder id=”CPH” runat=”server”></asp:contentplaceholder>
</div>
</form>
</body>
</html>

Now add a new web page (Deafault.aspx) to your site and select Site.master as it’s master page. Put a textbox and a button. Change their IDs to txtName and btnTest respectively. Then add a Javascript function that will display your name entered in the Textbox when Show button is clicked.
Your code will look like as follows;

<%@ Page Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” Title=”Untitled Page” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”CPH” Runat=”Server”>
<asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
<asp:Button ID=”btnShow” runat=”server” Text=”Show ” OnClientClick=”IDIssue();”/>

<script type=”text/javascript”>
function IDIssue()
{
var txt=document.getElementById(‘txtName’);
alert(‘your name is ‘+ txt.value);
}
</script>
</asp:Content>

Now, view the Deafault.aspx page in browser. Enter your name in the TextBox and click the Show button. Anything happened??

Nothing!!! Why???

If you see the source of the Textbox from the browser, you will see this,

<input name=”ctl00$CPH$txtName” type=”text” id=”ctl00_CPH_txtName” />

The id you given to the Textbox has been Changed. The reason is, at design time master page has no idea about the controls of the Content page as it works like a container. It can have its own control also. In order to avoid the duplication of the IDs between the Master page and Content Page, the master page generates IDs using this format “Controlhierarchy_ContentPlaceHolderID_ControlID”. Hence, your JavaScript fails to find the Element that has the ID “txtName”.

How will you solve it??? The primary idea that can come in your mind; let see the source in the browser, take the ID and paste it in the JavaScript. This is not ideal. If the hierarchy of the Page’s Controls are changed then it will fail again. The best way to resolve this issue is register your script from server side code. You should put the following code segment in Page_Load event of Deafault.aspx.cs file.

ContentPlaceHolder cp = ContentPlaceHolder)Page.Master.FindControl(“CPH”);
TextBox tb = (TextBox)cp.FindControl(“txtName”);
ClientScript.RegisterClientScriptBlock(this.GetType(), “IDIssue”, string.Format(@”function IDIssue() {{ var txt=document.getElementById(‘{0}’); alert(‘your name is ‘+ txt.value); }}”, tb.ClientID), true);

Now, everything will go fine…………….

Blog at WordPress.com.