Tuesday, September 20, 2016

How to add controls dynamically in ASP.NET

In this article I will explain how to add controls dynamically. In some
scenarios there might come requirement to add controls programmatically.

Suppose there is a Panel control in a webpage and on Button click we have to
add a TextBox dynamically to it, the code is as follows :

C# Code :


  protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        txt.ID = "TextBox1";
        txt.Text = "abc";
        Panel1.Controls.Add(txt);
    }


PlaceHolder control provides a container for adding controls at any part of
the webpage. PlaceHolder has no HTML output of its own but it renders its
child elements.

Let me show a basic example by which a TextBox is added dynamically
to a PlaceHolder on a Button click.

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
Text="Submit" />
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs) :


    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        txt.ID = "TextBox1";
        txt.Text = "hello";
        PlaceHolder1.Controls.Add(txt);
       
    }

This will add TextBox to the PlaceHolder on clicking the Button.
The above one is a basic case but if we want to display or access the added
control even on PostBack we cannot use this method as dynamic Controls 
will not be rendered on PostBack unless it is recreated in Page load function.
Because dynamically added controls are not stored in the ViewState as they
are created late after the Page's ViewState is generated.

Page's life cycle in short is as following :
(1) Instantiation
(2) Initialization
(3) Load ViewState
(4) Page Load
(5) Save ViewState

To overcome this it is best to create dynamic controls in Page_Init function.

C# Code (.aspx.cs) :

  protected void Page_Init(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        txt.ID = "TextBox1";
        txt.Text = "hello";
        PlaceHolder1.Controls.Add(txt);
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)PlaceHolder1.FindControl("TextBox1");
        txt.Text = "From Button1";
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)PlaceHolder1.FindControl("TextBox1");
        txt.Text = "From Button2";
    }

Next I will show an example of adding EventHandlers to the dynamically
created Control.

Suppose there is a PlaceHolder to which a TextBox and a Button are added
dynamically and EventHandler of Button click is also added dynamically.
On clicking that Button it will change the text of that TextBox.
The sample code is as follows:

    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        txt.ID = "TextBox1";
        txt.Text = "hello";
        PlaceHolder1.Controls.Add(txt);

        Button btnSubmit = new Button();
        btnSubmit.ID = "btnSubmit";
        btnSubmit.Text = "Submit";
        btnSubmit.Click += new EventHandler(btnSubmit_Click);
        PlaceHolder1.Controls.Add(btnSubmit);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)PlaceHolder1.FindControl("TextBox1");
        txt.Text="hi";
    }


Monday, September 19, 2016

How to use AJAX CalendarExtender Control

In this article I will explain how to use AJAX CalendarExtender Control that displays a
Calendar on click of a TextBox or an Image or an ImageButton or a Button and from
which date can be selected and displayed on a TextBox.

For using AJAX controls, first we have to add reference of AjaxControlToolKit.dll
to our Application and add AJAX Controls to the ToolBox.

Let me show the basic example of displaying Calendar when user clicks on a TextBox and
selected date is displayed on the TextBox. For this I have added TextBox control and Ajax CalendarExtender control to the webform. Also we have to add ScriptManager for the AJAX
controls to work. HTML code looks like this :

HTML Code(.aspx):

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1"
            PopupButtonID="TextBox1">
        </cc1:CalendarExtender>
    </div>
    </form>
</body>
</html>

Output :





















If we want to specify the format of the date we can use the property named Format of CalendarExtender as following :

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1"
            PopupButtonID="TextBox1"  Format="dd/MM/yyyy">
</cc1:CalendarExtender>

Next I will show an example of displaying Calendar on clicking on an image. Here we have to specify the PopupButtonID as ID of the Image Control.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/cal.png"/>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1"
            PopupButtonID="Image1"  Format="dd/MM/yyyy">
</cc1:CalendarExtender>


Output :




















Similarly we can use PopupButtonID as that of ImageButton as following:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/cal.png"/>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1"
            PopupButtonID="ImageButton1"  Format="dd/MM/yyyy">
</cc1:CalendarExtender>

Also we can use PopupButtonID as that of a Button as following :

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server"  Text="Show Calendar"/>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1"
            PopupButtonID="Button1"  Format="dd/MM/yyyy">
</cc1:CalendarExtender>


Also in case if TextBox is inside TemplateField of a GridView, we can provide CalendarExtender control to it.

Friday, September 16, 2016

Random Methods in ASP.NET

Random Class :


Random class in ASP.NET is used to generate pseudo-random numbers. 

Random numbers are numbers that has no specific sequence. It is useful in
some cases in Programming where we want to display results randomly.

Two constructors of Random class are the following :

(1) Random() which initializes the Random class using time dependent default
seed value.

(2) Random(Int32) which initializes the Random class using the specified integer 
seed value.

Random Methods :


(1) Next() which returns a non-negative random integer.
     For eg.

     Random ran = new Random();
     int i = ran.Next(); 

The output will be a positive random integer and it differs each time we run.

(2) Next(Int32) which returns a non-negative random integer less than the specified
     limit.
     For eg.

     Random ran = new Random();
     int i = ran.Next(10); 

The output will be a positive random integer less than 10.

(3) Next(Int32,Int32which returns a random integer between the specified
     limit which can be positive or negative integer values
     For eg.

     Random ran = new Random();
     int i = ran.Next(-3,3); 

The output will be a random integer between -3 and 3.

(4) NextBytes(Byte[]) which fills the elements of specified byte array with random
numbers.
For eg.

     Random ran = new Random();
     Byte[] b= new Byte[2];
     ran.NextBytes(b); 

This fills the elements of byte array with random numbers.

(5) NextDouble(which returns a random floating point number greater than or 
equal to 0.0 and less than 1.0
For eg.

     Random ran = new Random();
     double d = ran.NextDouble();

Samples using Random :


I will show one example by which a name is selected from an array list of names
on Button click in ASP.NET.

C# Code :

 protected void Button1_Click(object sender, EventArgs e)
 {
        string[] names = { "Mili", "Dia", "Mary", "Ria", "Tom", "John", "Abel" };
        int selectedindex = ran.Next(0, names.Length);
        Response.Write("Selected person is " + names[selectedindex]);
 }

Here we can see the output of single selected person which is picked randomly
from the array list and hence when each time it is run, we get different person.

Next I will show another example by which on each page load it will display
two featured Advertisements selected randomly on any part of a webpage in a
GridView.

C# Code :

protected void Page_Load(object sender, EventArgs e)
{
      DisplayAd();
}

protected void DisplayAd()
{
        Random rn = new Random();
        DataSet ds = new DataSet();
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        using (SqlConnection dbConnection = new SqlConnection(connectionString))
        using (SqlCommand dbCommand = new SqlCommand())
        {

            dbCommand.CommandText = "select * from Ads where featured=1";
            dbCommand.Connection = dbConnection;
            dbConnection.Open();

            SqlDataAdapter da = new SqlDataAdapter(dbCommand);
            da.Fill(ds);

        }
        int[] arr = new int[2];
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                int selectedindex = ran.Next(0, ds.Tables[0].Rows.Count);
                arr[0] = selectedindex;
                int selectedindex2 = ran.Next(0, ds.Tables[0].Rows.Count);
                arr[1] = selectedindex2;
            }
        }
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            if (i != arr[0] && i != arr[1])
                ds.Tables[0].Rows[i].Delete();
        }
        GridView1.DataSource = ds;
        GridView1.DataBind();
}

Here when each time the page loads and also on refresh it will display two different
Advertisements randomly.

Notes :

In case of generating random numbers multiple times in an Application, it is 
always best to avoid multiple instantiations of Random class. That is, in such 
cases create one common object of a Random class  and use that same object in places 
where we require. This avoids repetitions and also improves performance as 
creating and initializing Random object is an expensive process.

Random classes are not thread safe and hence to be carefully handled when we
call Random methods from multiple threads. 

Monday, September 5, 2016

Difference between ExecuteNonQuery, ExecuteReader and ExecuteScalar Functions

In this article I will explain the differences and scenarios of  ExecuteNonQuery,
ExecuteReader and ExecuteScalar Functions of SqlCommand Class of ADO.NET.

ExecuteNonQuery :


ExecuteNonQuery executes the SQL statement and returns an integer value that represents 
the number of rows affected. It is basically used for operation that doesn't return value and
change the data in a database with INSERT, UPDATE or DELETE  Query. Even though not 
used widely, it is also used for catalog operations like creating database objects like table.

With any other SQL Queries other than INSERT,UPDATE or DELETE, return value is -1.
Also in case if rollback occurs, it returns -1.

If there is any trigger associated with INSERT or UPDATE query, it will return both the
number of rows affected by the INSERT or UPDATE and the number of rows affected
by the trigger.

For eg. there is an insert function to insert values to Agents Table as :

public int AddAgent(int AgnNo, string Name, int Tel)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        int rowsAffected = 0;
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "insert into Agents(AGN_NO,AGN_NAME,AGN_TEL) values       (@AgnNo,@Name,@Tel)";
            cmd.Connection = conn;
            conn.Open();

            cmd.Parameters.Add(new SqlParameter("@AgnNo", AgnNo));
            cmd.Parameters.Add(new SqlParameter("@Name", Name));
            cmd.Parameters.Add(new SqlParameter("@Tel", Tel));
            rowsAffected = cmd.ExecuteNonQuery();
            conn.Close();

        }
        return rowsAffected;
    }

Here this function returns 1 if inserted successfully.

Next is the example for Update Query :

public int UpdateAgent(int AgnNo, string Name, int Tel)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        int rowsAffected = 0;
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "Update Agents set AGN_NAME=@Name,AGN_TEL=@Tel where AGN_NO=@AgnNo";
            cmd.Connection = conn;
            conn.Open();

            cmd.Parameters.Add(new SqlParameter("@AgnNo", AgnNo));
            cmd.Parameters.Add(new SqlParameter("@Name", Name));
            cmd.Parameters.Add(new SqlParameter("@Tel", Tel));
            rowsAffected = cmd.ExecuteNonQuery();
            conn.Close();

        }
        return rowsAffected;
    }

Here also this function returns 1 if updated successfully.

Example for Delete Query is as following :

public int DeleteAgent(int AgnNo)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        int rowsAffected = 0;
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "Delete From Agents where AGN_NO=@AgnNo";
            cmd.Connection = conn;
            conn.Open();

            cmd.Parameters.Add(new SqlParameter("@AgnNo", AgnNo));
            cmd.Parameters.Add(new SqlParameter("@Name", Name));
            cmd.Parameters.Add(new SqlParameter("@Tel", Tel));
            rowsAffected = cmd.ExecuteNonQuery();
            conn.Close();

        }
        return rowsAffected;
    }

Here also this function returns 1 if deleted successfully.

ExecuteReader :


This method is used for fetching records from database using SELECT statement
or Stored Procedure with SELECT Query.

ExecuteReader basically sends the CommandText to the Connection and builds a
SqlDataReader which provides a forward-only way of reading rows from the 
database.

For eg.

public SelectAgents()
{
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "Select * From Agents";
            cmd.Connection = conn;
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string Name = dr["AGN_NAME"].ToString();
                string Tel = dr["AGN_TEL"].ToString();

                Response.Write("Name is : "+ Name);
                Response.Write("Tel is : "+ Tel);
            }
            conn.Close();

        }
     
  }

ExecuteScalar :


ExecuteScalar method executes the query and returns the first column of the first row
of the result set. It is used in case of getting single value from the database.

Below is the example for Select statement :

public int GetAgentCount()
{
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        using (SqlConnection conn= new SqlConnection(connectionString))
        using (SqlCommand cmd= new SqlCommand())
        {
            cmd.CommandText = "select count(*) from Agents";
            cmd.Connection = dbConnection;
            conn.Open();
            return (int) cmd.ExecuteScalar();
        }

}

It can also be used for getting the identity column value of the inserted row.
Below is the example:

public int AddAgent(int AgnNo, string Name, int Tel)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        int id= 0;
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "insert into Agents(AGN_NO,AGN_NAME,AGN_TEL) values       (@AgnNo,@Name,@Tel); Select CAST(scope_identity() as int)";
            cmd.Connection = conn;
            conn.Open();

            cmd.Parameters.Add(new SqlParameter("@AgnNo", AgnNo));
            cmd.Parameters.Add(new SqlParameter("@Name", Name));
            cmd.Parameters.Add(new SqlParameter("@Tel", Tel));
            id=  (int) cmd.ExecuteScalar();
            conn.Close();

        }
        return id;
    }