Thursday, February 25, 2010

Efficient best Syntax to Open a SqlConnection in Asp.Net 2.0 3.5




Please visit my new Web Site WWW.Codedisplay.com



To describe the best way to open sql server connection in asp.net here i am choosing to bind the gridview because in most of the cases the major task is to bind GridView data. You can make more generous method to collect sql server data but here my intension is to show you how you can open sql server connection efficiently.













Please have a look at the code sample:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL= "SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";
            

            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

The best practice is to wrap up all code under using statement. If you look at the code you will find that i have wrapped up all code under connection object as well as sql command. Keep in mind that when corresponding "using" statement reached at the end then asp.net automatically clear all variables immediately within the scope. You do not need to dispose those manually. Such as here i don't close the connection, sqlcommand. For ease understanding here i am using datatable. You can use any ado.net component whichever you like. But keep in mind to wrap up the connection object within "Using" statement.
This is my message to you.

Kick expire close all user connection from Sql Server 2005 / 2008 Database




Please visit my new Web Site WWW.Codedisplay.com



In some cases DBA's need to expire or close all connections from SQL server 2005 / SQL server 2008 database such as for attach detach DataBase, Make DB readonly, perform maintenance tasks etc. For such type of issues DBA wants to get exclusive access to the database. To do so, you can set the database to Single User Mode, which permits only one database connection at a time. At that moment if other users try to access the database while you are working on that active connection, they will receive an error.










To bring a database to the single user mode, use the following query:
ALTER DATABASE DATABASENAME SET SINGLE_USER

Users those already connected to the db when you run this command, they will not be disconnected. Instead the 'SET SINGLE_USER' command will wait till the others have disconnected. If you want to override this scenario and forcefully disconnect other users, then use the following query:
ALTER DATABASE DATABASENAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE

OK now your database immediately move to the single user mode. Now After completion of your maintenance task you need to go back to multiuser mode by applying another TSQL command which is given below:
ALTER DATABASE DATABASENAME SET MULTI_USER

So now hope you can gain quick access in your database by applying the above TSQL command.

Wednesday, February 24, 2010

How To get RowIndex of Asp.Net GridView in the RowCommand Event




Please visit my new Web Site WWW.Codedisplay.com



As we know that if we add any button control or image button control or link button within the GridView and click to generate postback event then GridView RowCommand Event will fire. But the problem is from this RowCommand method we did not easily get the cliclked or selected GridView row index number. To get the RowIndex of Asp.Net GridView in the RowCommand Event we have two options.

1. Using CommandSource object
2. Using CommandArgument property

Ok our target is to add an action button within GridView rows & get the RowIndex number from RowCommand Method like below:
GridView RowCommand to get RowIndex

Using CommandSource object:
To do that first add a GridView with a LinkButton in a template field like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />

                <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" ></asp:LinkButton> 
                </ItemTemplate> 
                <EditItemTemplate> 
                </EditItemTemplate> 
                </asp:TemplateField>             

         </Columns>
        </asp:GridView>
        <br />
        <hr />

        <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>

Now go to the design mode. Right click on GridView to get property window. From event list select RowCommand event. Double click to write the method code like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = oItem.RowIndex;
            lblRowIndex.Text = "Row Index = "+RowIndex.ToString();
        }
    }

Now run the page & click on any one of the Action linkbutton. The label shows the RowIndex number of your clicked Action button.


Using CommandArgument property:
To do that first add a GridView with a LinkButton in a template field like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />

                <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' ></asp:LinkButton> 
                </ItemTemplate> 
                <EditItemTemplate> 
                </EditItemTemplate> 
                </asp:TemplateField>             

         </Columns>
        </asp:GridView>
        <br />
        <hr />

        <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>
Now go to the design mode. Right click on GridView to get property window. From event list select RowCommand event. Double click to write the method code like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            int RowIndex = Convert.ToInt32((e.CommandArgument).ToString());
            lblRowIndex.Text = "Row Index = "+RowIndex.ToString();
        }
    }

Hope now you can findout the RowIndex number of any row of the GridView whatever the control is.
Happy coding !!

ERROR: The process cannot access the file because it is being used by another process




Please visit my new Web Site WWW.Codedisplay.com



In most of the cases specially in image manipulation time developers faced an error like:
The process cannot access the file because it is being used by another process.

The error happened because when you try to access an object of image or Font just immediately after you use it. Because the dot net framework does not destroy the resource before you calling. To resolve this problem you have to release the resource first & then you can use it again. To ensure freeing the unmanaged resource is a tough job but doable.

Asp.net provides us "using" statement to wrap up your respective code within using statement. This statement ensure that the object will be destroyed just after its scope even if any error occured within the block. So the solution is when you want to manipulate any image type object or Font or any file then wrap up all code within the using statement. The sample format is given below:
using (System.Drawing.Image Img = System.Drawing.Image.FromFile(Server.MapPath("Images\\YourImageName.jpg"))) 
{ 
 // Do whatever you want 
}

So it would be better to practice always wrap up your relevant code within "Using" statement.

Tuesday, February 23, 2010

Convert DataTable to DataView in Asp.net C# in VS 2008




Please visit my new Web Site WWW.Codedisplay.com



The following sample code will demonstrate the convertion from DataTable to DataView in C# in VS 2008.

In VS 2008, DataView have one method which accept datatable as input parameter and it return the converted result as dataview by using DataView(). Ok now look at the converting DataTable to DataView example code:










protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Create dynamic data table.
            DataTable dt = new DataTable();


            // Create columns
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            dt.Columns.Add("Age", typeof(System.Int32));

            DataRow  oItem = dt.NewRow();
            oItem[0] = "Shawpnendu";
            oItem[1] = "Bikash";
            oItem[2] = 32;


            // Add new Datarow to data table.
            dt.Rows.Add(oItem);

            oItem= dt.NewRow();
            oItem[0] = "Bimalendu";
            oItem[1] = "Bikash";
            oItem[2] = 27;


            // Add new Datarow to data table.
            dt.Rows.Add(oItem);


            // Convert data table to dataview.
            DataView dv= new DataView(dt);
            

     // Now ready to use this dataview.
            Response.Write("DataView Row Count: "+dv.Count.ToString());
        }
    }
Look at the code above its self explanatory. So i hope that no need any explanation.

How to convert SqlDataReader or DataReader to DataSet in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



In some cases most of the asp.net C# vb.net developers need to convert or converting SqlDataReader or DataReader to a DataSet to meet some technical challenges. Here i will show you converting SqlDataReader to a DataSet in a simple way. The code sample is given below:












protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sql = "SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            using (SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString))
            {
                oConn.Open();
                SqlCommand cmd = new SqlCommand(sql, oConn);
                System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
                ds.Tables.Add(dt);
            }

            Response.Write("Dataset Row count: "+ds.Tables[0].Rows.Count.ToString());
        }
    }
Look at the code its self explanatory. So i hope that no need any explanation.

How to convert SqlDataReader or DataReader to DataTable in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



In many cases we need to convert or converting SqlDataReader or DataReader to a DataTableto meet some technical challenges. Here i will show you converting SqlDataReader to a DataTable in a simple way. The code sample is given below:













protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sql = "SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";
            DataTable dt = new DataTable();
            using (SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString))
            {
                oConn.Open();
                SqlCommand cmd = new SqlCommand(sql, oConn);
                System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
            }

            Response.Write("Datatable row count: "+dt.Rows.Count.ToString());
        }
    }
Look at the code its self explanatory. So i hope that no need any explanation.

Monday, February 22, 2010

How to read GridView row column data using javascript




Please visit my new Web Site WWW.Codedisplay.com



In some cases we need to read GridView row column data using javascript specially for search purpose. Also there were lots of reason to read GridView data using javascript. If you can read gridview data from a javascript function then you can implement lot of eye catching interface for your client.

The below javascript function wiil read gridview contents or loop through gridview rows:









function Read_Data ()
    {
        var str='';
        var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
        for(var row=1; row<Grid_Table.rows.length; row++)
        {
            for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
            {
                if(col==0)
                    if(document.all)
                        str=str+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+Grid_Table.rows[row].cells[col].textContent;
                else
                    if(document.all)
                        str=str+'--'+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+'--'+Grid_Table.rows[row].cells[col].textContent;
            }
            str=str+'\n';   
        }
        alert(str);
        return false;
    }    
If you need to know the gridview row header name then start first loop from 0.

For a complete example you can add an aspx page & copy the below html markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="javascript_GridView_Read.aspx.cs" Inherits="javascript_GridView_Read" %>

<!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>Read GridView Contents using javascript</title>
<script type="text/javascript">
    function Read_Data ()
    {
        var str='';
        var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
        for(var row=1; row<Grid_Table.rows.length; row++)
        {
            for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
            {
                if(col==0)
                    if(document.all)
                        str=str+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+Grid_Table.rows[row].cells[col].textContent;
                else
                    if(document.all)
                        str=str+'--'+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+'--'+Grid_Table.rows[row].cells[col].textContent;
            }
            str=str+'\n';   
        }
        alert(str);
        return false;
    }    
</script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>
        </asp:GridView>
        <br />
        <hr />
        <br />
        <asp:Button runat="server" ID="cmdRead" Text="Javascript to read gridview data" OnClientClick=" return Read_Data();" />
    </div>
    </form>
</body>
</html>
The serverside code is given below:
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 javascript_GridView_Read : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
        }
    }
}
The output looks like:
javascript to read gridview

Hope now you can read gridview content using javascript. Happy programming.

Script tested for:
1. Internet Explorer
2. Opera
3. Mozilla Firefox
4. Google Chrome

Thursday, February 18, 2010

Check user internet connectivity using Asp.Net C#




Please visit my new Web Site WWW.Codedisplay.com



In some cases specially for AJAX projects Asp.net C# VB.Net developers need to check user internet connection before attempting to connect to remote server. Also another important usage is for dashboard where after certain time interval you may need to know does the user connected with the network or not. Here in this article i will describe how one can find user internet connectivity using asp.net C# server side code.

The strategy is to start download a page from server. If you can download means you are connected to the internet otherwise not. Here i am using Google page but you can use any simple page for better performance. Look at the below code:






WebClient workstation = new WebClient();
        byte[] data = null;

        try
        {
            data = workstation.DownloadData("http://www.google.com");
        }
        catch (Exception ex)
        {
        }
        
        if (data != null && data.Length > 0) 
            lblCaption.Text="You are connected.";
        else
            lblCaption.Text="You are not connected.";
To complete an example first add a page in your project. Then write the below Markup Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Internet_Connectivity.aspx.cs" Inherits="Internet_Connectivity" %>

<!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>How to check user internet connection</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label runat="server" ID="lblCaption" Font-Bold="true" ForeColor="DarkBlue">To test your connection click below</asp:Label>
    <br />
    <br />
    <asp:Button runat="server" ID="cmdCHeck" Text="Check Connectivity" OnClick="cmdCHeck_Click" />
    </div>
    </form>
</body>
</html>
Under code behind the complete code is given below:
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.Net;

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

    }
    protected void cmdCHeck_Click(object sender, EventArgs e)
    {
        WebClient workstation = new WebClient();
        byte[] data = null;
        try
        {
            data = workstation.DownloadData("http://www.google.com");
        }
        catch (Exception ex)
        {
        }
        if (data != null && data.Length > 0) 
            lblCaption.Text="You are connected.";
        else
            lblCaption.Text="You are not connected.";
    }
}
Don't forget to add System.Net namespace into your page.

The output will be:
Check Internet Connection

Hope now you can check whether user connected to the internet or not.

Wednesday, February 17, 2010

How to get readonly textbox value in codebehind or CS file




Please visit my new Web Site WWW.Codedisplay.com



As we know that when we declare a textbox as readonly then we didnot get value from that readonly textbox from code file. Because asp.net rejects any changes in readonly textbox after postback. Here in this article i will describe ASP.NET Read Only TextBox lose client side changes, values across post back? Why Readonly Text box values are empty in code behind ? Issue in Retrieving textbox value when readonly = true in codebehind.? The real thing is when you declare a textbox as readonly in design mode and assign a value using a javascript function then from code file you did not get the value in server side. Its a bug.Its a problem for developers. There is a workaround on this issue which i will share with you. The solution is simple.

Solution:
1. Dont assign readonly property=true in design mode.
2. Bind the readonly property from serverside page load event like:


if (!IsPostBack)
            txt_ReadOnly.Attributes.Add("readonly", "readonly");
Hope now your problem has been resolved.

Ok now i am going to create an example. In this example first take a textbox in your page with readonly=true. like:
<asp:TextBox runat="server" ID="txt_ReadOnly" ReadOnly="true"></asp:TextBox>
Then add two button. One is to set some value into the readonly textbox using javascript. And another button will try to read the readonly textbox value that i have set before. Look at this moment you would not get the value & the readonly textbox will loose the value after second button postback. Now remove the readonly property from design page. So now your complete HTML markup will look like:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="readonly_textbox.aspx.cs" Inherits="readonly_textbox" %>

<!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>Read readonly textbox value in code file</title>
    <script type="text/javascript">
    function setValue()
    {
        document.getElementById('<%= txt_ReadOnly.ClientID %>').value="Hello World!";
        return false;
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txt_ReadOnly" ReadOnly="true"></asp:TextBox>
    <br />
    <br />
    <asp:Button runat="server" ID="cmdSet" Text="Set value in readonly textbox" OnClientClick="return setValue();" />
    <asp:Button runat="server" ID="cmdGetValue" Text="Get value from readonly textbox" OnClick="cmdGetValue_Click" />
    </div>
    </form>
</body>
</html>
Here you found that under first button i have assigned a javascript function to write something in the readonly textbox. Now under second button just write the readonly textbox value into the form. Also do not forget add the readonly attribute under page_load event like below. So your server side code will look like:
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 readonly_textbox : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            txt_ReadOnly.Attributes.Add("readonly", "readonly");
    }
    protected void cmdGetValue_Click(object sender, EventArgs e)
    {
        Response.Write(txt_ReadOnly.Text);
    }
}
The output will look like:
Readonly textbox problem
So now hope you understand what is the problem & how we can resolve it.

Tuesday, February 16, 2010

How to Loop through GridView Rows Asp.net C#




Please visit my new Web Site WWW.Codedisplay.com



This is a small tips for asp.net C# vb.net novice developers. We can loop through GridView rows using two ways:

1. Use GridViewRow class to loop through or navigate the GridView rows from outsite the GridView control's event.

2. Use general for loop based on GridView Rowcount method.

In this article i will generate the following interface:
Loop gridview rows

Loop through GridView rows using GridViewRow class:
protected void cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
Loop through GridView rows using simple For loop:
protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "
";
            ltrlText.Text = str;
    }
To generate the example the complete HTML markup code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridview_loop.aspx.cs" Inherits="gridview_loop" %>

<!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>How to loop through gridview rows</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>
        </asp:GridView>
        <br />
        <hr />
        <asp:Button runat="server" ID="cmdGridViewRow" Text="Loop GridViewRow" OnClick="cmdGridViewRow_Click" />
        <asp:Button runat="server" ID="cmdRowCount" Text="Loop Row Count" OnClick="cmdRowCount_Click" />
        <br />
        <hr />
        <br />
        <asp:Literal runat="server" ID="ltrlText"></asp:Literal>
    </div>
    </form>
</body>
</html>
The complete server side code is:
using System;
using System.Web.UI.WebControls;

public partial class gridview_loop : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
        }
    }
    protected void cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
    protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "<br />";
            ltrlText.Text = str;
    }
}
Hope now you can loop through all the rows within a gridview.

How to Set Internet Explorer IE as Default Browser




Please visit my new Web Site WWW.Codedisplay.com



Do you really like internet explorer? If yes and plan to use it for all of your Internet browsing needs, you have to consider making internet explorer or IE as your default browser. Basically it was happen when you install more than one browser than you may dont get Internet Explorer as your default browser. Here in this article i will show you how one can set internet explorer as his deafult browser.

Steps to follow:
1. Open Internet Explorer on your computer.
2. Click on 'Tools' from toolbar menu.
3. Select 'Internet Options' from the list of choices.
4. Go to the 'Programs' tab.
5. Find the 'Default Web Browsers' heading.
6. Click on the 'Make Default' button.
Default Internet explorer IE
7. Click 'OK.' Your default Internet browser is now Internet Explorer.

To test your new settings to find Internet Explorer as your default browser, click on any Web link from your computer will now open by Internet explorer. If you click on a link from an email, the Web site should automatically load in a new Internet Explorer window or tab.

Monday, February 8, 2010

Apple rainbow logo t-shirt




Please visit my new Web Site WWW.Codedisplay.com



Anything with Apple is going to be a hit at the moment. This T Shirt has a cool image of the enterprise but it is much more than that, as this has a flashing logo not fixed. Means this logo is lives!!

See here:
Apple light t-shirt

Specification:

The T-Qualizer is made from 100% cotton.
1 x Battery pack and sound sensor.
Panel is powered by a detachable battery pack.
The battery pack can be unplugged for washing the t-shirt.
The t-shirt is hand wash only.
Requires 4 x AAA Batteries (not included).
Price varies between $20 and $45

Source: Internet

Sunday, February 7, 2010

How to disable multiple button click in Asp.net




Please visit my new Web Site WWW.Codedisplay.com



Disabling or preventing multiple mouse button click event on Asp.net page is a common task. Specially when you want to develop an e-commerce site client must want to disable the payment button after first click of the user. So that user can't click twice or double or multiple time.Normally we have used an onclick javascript event to diable the button after first click. In Asp.net each serverside control has already a onclick event to do the same thing in asp.net.

Basically my approach is different from others. Here i will register the javascript onclick attributes in the run time means page_load event & after that i give the command to execute the server side event.

To understand what i am trying to do look at the below sequences where when user click on the button i will disable the button & after completion the button will enable soon. If you redirect from this page then no problem.

Prevent_multiple_click

Just use the below line code under page_load event:
cmdSubmit.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(cmdSubmit,"").ToString());
Where cmdSubmit is our button which we dont want to click twice or more.

Now complete ths example add a page in your project. The HTML MARKUP code is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Disable_Multiple_button_click.aspx.cs" Inherits="Disable_Multiple_button_click" %>

<!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>How to disable multiple button click</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button runat="server" ID="cmdSubmit" Text="Clcik Me" OnClick="cmdSubmit_Click" />
    </div>
    </form>
</body>
</html>
The complete serverside code is given below:
using System;


public partial class Disable_Multiple_button_click : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        cmdSubmit.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(cmdSubmit,"").ToString());
    }
    protected void cmdSubmit_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(5000);
        Response.Write("I have clicked : "+DateTime.Now.ToString());
    }
}
Hope now you can restrict or prevent the user from twice or more than one or from multiple mouse click.

How to validate Integer Decimal Double DateTime values in Asp.Net C#




Please visit my new Web Site WWW.Codedisplay.com



In most cases asp.net C# VB.Net developers need to check or validate user input for integer, decimal & DateTime. Asp.net C# provides us an easy way to validate those user inputs from server side. Here in this small article i will show you how one can validate using Asp.Net. Basically TryParse boolean returntype method will help us to check user inputs. It Converts the specified string representation of a Date and time / Integer / Decimal to its DateTime equivalent Integer equivalent Decimal equivalent and returns a value that indicates whether the conversion succeeded or not. In the below example i will show you to validate DateTime, Integer & Decimal values validation.

The output like:
How to validate integer,datetime & Decimal datatatype using asp.net

To do that add a page in your project & paste the below HTML MARKUP:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="validate_int_datetime.aspx.cs" Inherits="validate_int_datetime" %>

<!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>How to validate integer double numeric datetime in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lbl_integer" runat="server" Text="Enter Integer: "></asp:Label>
    <asp:TextBox runat="server" ID="txt_integer"></asp:TextBox>
    <asp:Button ID="cmd_integer" runat="server" Text="Click to check" OnClick="cmd_integer_Click" />
    <asp:Label ID="lbl_integer_result" runat="server" Font-Bold="True"></asp:Label>
    <br />
    <hr />
    <br />
    <asp:Label ID="lbl_decimal" runat="server" Text="Enter Decimal: "></asp:Label>
    <asp:TextBox runat="server" ID="txt_decimal"></asp:TextBox>
    <asp:Button ID="cmd_decimal" runat="server" Text="Click to check" OnClick="cmd_decimal_Click" />
    <asp:Label ID="lbl_decimal_result" runat="server" Font-Bold="True"></asp:Label>
    <br />
    <hr />
    <br />
    <asp:Label ID="lbl_Datetime" runat="server" Text="Enter datetime: "></asp:Label>
    <asp:TextBox runat="server" ID="txt_Datetime"></asp:TextBox>
    <asp:Button ID="cmd_Datetime" runat="server" Text="Click to check" OnClick="cmd_Datetime_Click" />
    <asp:Label ID="lbl_datetime_result" runat="server" Font-Bold="True"></asp:Label>
    </div>
    </form>
</body>
</html>
Now in codebehind write the below code:
using System;

public partial class validate_int_datetime : System.Web.UI.Page
{
    Int32 Check_Integer;
    decimal check_decimal;
    DateTime check_Datetime;
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void cmd_integer_Click(object sender, EventArgs e)
    {
        if(Int32.TryParse(txt_integer.Text,out Check_Integer))
            lbl_integer_result.Text="Integer Validation Successfull.";
        else
            lbl_integer_result.Text = "Invalid Integer!!";
    }
    protected void cmd_decimal_Click(object sender, EventArgs e)
    {
        if (decimal.TryParse(txt_decimal.Text, out check_decimal))
            lbl_decimal_result.Text = "Decimal Validation Successfull.";
        else
            lbl_decimal_result.Text = "Invalid Decimal!!";
    }
    protected void cmd_Datetime_Click(object sender, EventArgs e)
    {
        if (DateTime.TryParse(txt_Datetime.Text, out check_Datetime))
            lbl_datetime_result.Text = "Datetime Validation Successfull.";
        else
            lbl_datetime_result.Text = "Invalid Datetime!!";
    }
}
Check the code how i use TryParse to validate datatypes.

Hope now you can validate any primitive datattypes using asp.net.

Friday, February 5, 2010

Javascript to check multiline textbox max length asp.net C# VB.Net




Please visit my new Web Site WWW.Codedisplay.com



Most of the asp.net developers knew that maxlength property of textbox will work even the multiline property set to true. But it doesnot work. To check or restrict maxlength of a multiline textbox you have to develop a javascript fucntion. In this article i will show you how you can limit or restrict multine textbox character limit using javascript.

If you are looking for textarea then click here.

Output Like:
maxlength check textbox multiline

The javascript function is given below:
<script type="text/javascript">
        function ismaxlength(objTxtCtrl,nLength)
        {
            if (objTxtCtrl.getAttribute && objTxtCtrl.value.length>nLength)
                objTxtCtrl.value=objTxtCtrl.value.substring(0,nLength)
            
            if(document.all)
                document.getElementById('lblCaption').innerText=objTxtCtrl.value.length +' Out Of '+nLength;
            else
                document.getElementById('lblCaption').textContent=objTxtCtrl.value.length +' Out Of '+nLength;
            
        }
    
</script>
Call javascript from multiline TextBox:
<textbox columns="50" id="txtMultiline" onkeyup="return ismaxlength(this,255)" rows="5" runat="server" textmode="MultiLine"></textbox>    
        
<label id="lblCaption" style="font-family: Tahoma; font-size: 1em; font-weight: bold;"></label>
Complete HTML markup of my example page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Multiline_limit.aspx.cs" Inherits="Multiline_limit" %>

<!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>How to check mutiline textbox max length using javascript</title>
    <script type="text/javascript">
        function ismaxlength(objTxtCtrl,nLength)
        {
            if (objTxtCtrl.getAttribute && objTxtCtrl.value.length>nLength)
                objTxtCtrl.value=objTxtCtrl.value.substring(0,nLength)
            
            if(document.all)
                document.getElementById('lblCaption').innerText=objTxtCtrl.value.length +' Out Of '+nLength;
            else
                document.getElementById('lblCaption').textContent=objTxtCtrl.value.length +' Out Of '+nLength;
            
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtMultiline" runat="server" Rows="5" Columns="50" TextMode="MultiLine" onkeyup="return ismaxlength(this,255)" ></asp:TextBox>    
        <br />
        <label id='lblCaption' style="font-family:Tahoma;font-size:1em;font-weight:bold"></label>
    </div>
    </form>
</body>
</html>
Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Thursday, February 4, 2010

How to use more than one DataKeyNames of a GridView in asp.net 2.0 / 3.5




Please visit my new Web Site WWW.Codedisplay.com



In my previous article i have described "how we can remove multiple GridView rows like gmail deletion at a time". This article is the continution article. In this article i will modify the base article class file to show you how one can use more than one datakeynames in a gridview as well as in editing time or in GridView manipulation time how one can read more than one datakeynames that you have assigned in design time or in runtime. The real example is let you have a product table. Which contains productid,brandid,category id as well. Also a product may have a different category. So when you show a list of products then you have to pick a product with productid, CategoryID for deletion or modification. Here i will describe how.

DataKeyNames is the property to define Read-only primary key or composite primary key like fields in a GridView control. We can also add some more fields to this property separated by commas.

At first have a look at the below example how to assign more than one or multiple datakeynames in a gridview:
<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID,BrandID,CategoryID" AutoGenerateColumns="false">
<HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="LightGray" />
<Columns>
    <asp:TemplateField HeaderText="Select">
    <ItemTemplate>
    <asp:CheckBox runat="server" ID="chk"/>
    </ItemTemplate>
    <HeaderTemplate>
    <input id="chkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" runat="server" type="checkbox" value="" />
    </HeaderTemplate>
    </asp:TemplateField>

     <asp:BoundField DataField="Name" HeaderText="Name"/>
     <asp:BoundField DataField="Description" HeaderText="Description" />
     <asp:BoundField DataField="Color" HeaderText="Color" />
</Columns>
</asp:GridView>
Secondly read the below codes how you can read more than one or multiple datakeynames in manipulation time:
public bool PerformDelete(GridView GV, string sTableName)
    {
        bool bSaved = false;
        string sClause = "";
        string sSQL = "";
        string sConstr = "";
        SqlConnection Conn;
        SqlCommand comm;

        sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
        foreach (GridViewRow oItem in GV.Rows)
        {
            if (((CheckBox)oItem.FindControl("chk")).Checked)
            {
                for (int i = 0; i < GV.DataKeyNames.Length; i++)
                    sClause =sClause+" AND "+ GV.DataKeyNames.GetValue(i) + "=" + GV.DataKeys[oItem.DataItemIndex][i].ToString();

                sSQL = "DELETE FROM " + sTableName + " WHERE 1=1"+sClause;
                // The above sql will generate like the below query
                // DELETE FROM product WHERE 1=1 AND ID=4 AND BrandID=2 AND CategoryID=4
                Conn = new SqlConnection(sConstr);
                using (Conn)
                {
                    try
                    {
                        Conn.Open();
                        comm = new SqlCommand(sSQL, Conn);
                        using (comm)
                        {
                            comm.CommandTimeout = 0;
                            comm.ExecuteNonQuery();
                            bSaved = true;
                        }
                    }
                    catch (Exception Ex)
                    {
                        bSaved = false;
                        // You can through error from here.
                    }
                }
            }
        }
        return bSaved;
    }
Since this article is a continution of previous one so for better understanding you can read the base article first & then read this article. But if you need only know the use of multiple datakeynames then hope my above example code segments is enough for you.

Wednesday, February 3, 2010

Enable disable show hide controls in grdview edit mode RowEditing or PreRender method




Please visit my new Web Site WWW.Codedisplay.com



In many asp.net (C# VB.Net) forum i found that developers ask how to enable or disable or show or hide asp.net server side controls like textbox,label,checkbox,checkboxlist,radiobutton,radiobuttonlist & dropdownlist or combo box in gridview edit mode. Everyone tries to find those controls within RowEditing event handler but they didn't get the control by using findcontrol method and editindex number. The findcontrol method will return null since in RowEditing eventhandler we didn't reference the controls in runtime data editing mode. But there is an alternative so that we can reference the above controls within gridview edit mode is PreRender method. In PreRender method we can access each edit template controls so that we can easily hide or show or enable or disable those controls.

If you want to read "DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode in Asp.Net" then click here.

I have added a method named GridView1_PreRender which is a sequence of above article. So you can read first the above article & then continue with this one.

My sugession is in RowEditing method you didn't get control reference use prerender method in the following way:
protected void GridView1_PreRender(object sender, EventArgs e)
    {
        if (this.GridView1.EditIndex != -1)
        {
            DropDownList cboSize =(DropDownList)GridView1.Rows[GridView1.EditIndex].FindControl("cboSize");
            if (cboSize != null)
            {
                // You can apply condition here
                cboSize.Enabled = false;
            }

        }
    }
The output:
Show hide enable disable controls in gridview edit mode

Hope now you can get gridview row index in edit mode to enable or disable or soh or hide controls conditionaly.

Tuesday, February 2, 2010

Javascript to read Master Page and Content Page controls data




Please visit my new Web Site WWW.Codedisplay.com



In many forums i found that asp.net c# vb.net developers ask expert how to read or access master page control from content page as well as how to get content page control from master page using clientside javascript. Thats why in this asp.net javascript tutorial i will explain how you can read or access content page controls from master page as well as read or access master page controls from content page by client side javascript function.

If you want to read "Read ASP.NET Master Page controls from Content Page and viceversa using server side code" then click here.







To do this example first add a master page in your project. Then add the below controls on master page like below:
<asp:Label ID="lblMaster" runat="server" Text="Master Label"></asp:Label>
<asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
<asp:Button ID="cmdChild" OnClientClick="return GetContentValue();" runat="server" Text="Read Content TexBox Value" />
Add a content page by attaching the above master page in your project and then add the below controls:
<asp:Label ID="lblChild" runat="server" Text="Child Label"></asp:Label>
<asp:TextBox ID="txtChild" runat="server"></asp:TextBox>
<asp:Button ID="cmdChild" OnClientClick="return GetMasterValue();" runat="server" Text="Read Master TexBox Value" />
Now add the below javascript method or function in the master page head section to read content page textbox control data like below:
<script type="text/javascript">
function GetContentValue()
{
    alert(document.getElementById('<%= ((TextBox)ContentPlaceHolder1.FindControl("txtChild")).ClientID %>').value);
    return false; 
}
</script>
Now add the below javascript method or function in the content page content section to read master page textbox control data like below:
<script type="text/javascript">
function GetMasterValue()
{
    alert(document.getElementById('<%=((TextBox)Master.FindControl("txtMaster")).ClientID %>').value);
    return false; 
}
</script>
Simple output like below:
Javascript to read master page & content page controls

My complete masterpage HTML markup is given below:
<%@ 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>Javascript to read content page controls</title>
<script type="text/javascript">
function GetContentValue()
{
    alert(document.getElementById('<%= ((TextBox)ContentPlaceHolder1.FindControl("txtChild")).ClientID %>').value);
    return false; 
}
</script>    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblMaster" runat="server" Text="Master Label"></asp:Label>
        <asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
        <asp:Button ID="cmdChild" OnClientClick="return GetContentValue();" runat="server" Text="Read Content TexBox Value" />
        <br />
        <hr />
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
My complete content page HTML markup is given below:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="child_form.aspx.cs" Inherits="child_form" Title="Javascript to read master page controls: " %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function GetMasterValue()
{
    alert(document.getElementById('<%=((TextBox)Master.FindControl("txtMaster")).ClientID %>').value);
    return false; 
}
</script>
<asp:Label ID="lblChild" runat="server" Text="Child Label"></asp:Label>
<asp:TextBox ID="txtChild" runat="server"></asp:TextBox>
<asp:Button ID="cmdChild" OnClientClick="return GetMasterValue();" runat="server" Text="Read Master TexBox Value" />
</asp:Content>
You can read any serverside control like dropdownlist, checkbox, radiobutton, checkboxlist, radiobuttonlist as well using the above javascript method with slight modification. Hope you can do whatever controls in master page or in content page.

Monday, February 1, 2010

Access ASP.NET Master Page controls from Content Page and viceversa




Please visit my new Web Site WWW.Codedisplay.com



In many forums i found that asp.net c# vb.net developers ask expert how to get or read master page control from content page as well as how to get or read content page control from master page. Thats why in this asp.net tutorial i will explain how you can access or read content page controls from master page as well as access or read master page controls from content page.

If you want to read master page & content page controls using javascript then click here.









To do it by a simple example add a master page and a content page in your project.
The HTML Markup is given below:
Master Page:
<%@ 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:Label ID="lblMaster" runat="server" Text="Master Label"></asp:Label>
        <asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
        <br />
        <hr />
        
 <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
Content Page:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="child_form.aspx.cs" Inherits="child_form" Title="Master & content page overview: " %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<asp:Label ID="lblChild" runat="server" Text="Child Label"></asp:Label>
<asp:TextBox ID="txtChild" runat="server"></asp:TextBox>

</asp:Content>
The server side code is given below:
Master Page:
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.FindControl("ContentPlaceHolder1");
            if (ContentPlaceHolder1 != null)
            {
                Label lblChild = (Label)ContentPlaceHolder1.FindControl("lblChild");
                TextBox txtChild = (TextBox)ContentPlaceHolder1.FindControl("txtChild");
                if (lblChild != null)
                    lblChild.Text = "My Child Label";
                if (txtChild != null)
                    txtChild.Text = "My Child TextBox";
            }
        }
    }
}
Content Page:
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class child_form : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label lblMaster=(Label)Master.FindControl("lblMaster");
            TextBox txtMaster = (TextBox)Master.FindControl("txtMaster");

            if (lblMaster != null)
                lblMaster.Text = "My Master Label";
            if (txtMaster != null)
                txtMaster.Text = "My Master TextBox";
        }
    }
}
If you look at my code then you will find that you can easily read master page controls from content page
by using Master.FindControl() method. And can read content page from master page by using this.FindControl method.

The output will be:
Master Content Overview

Hope now you can read master page controls & content page control from each other.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash