Ajax updatepanel example with triggers in asp.net

March 14, 2013 |

Introduction:


In this article I will explain what is Ajax updatepanel control, advantages of updatepanel control and how to use multiple updatepanels in asp.net.

Description:

Previously I explained many articles relating to 
Ajax. Now I will explain what is ajax updatepanel control and use of ajax updatepanel control in asp.net.
During work with our applications if we entered any values in textbox controls and click on a button in form we will see full postback of our page and we will lost all the controls values whatever we entered previously this happend because of postback. If we want to avoid this full postback of page and round trip to server we need to write much code instead of writing much code we can use ajax updatepanel control.
Ajax updatepanel will help us to avoid full postback of the page i.e., avoid refresh of the whole page content with postback and stop flickering of the page which is associated with a postback and allows only partial postbacks. By using Ajax updatepanel we can refresh only required part of page instead of refreshing whole page.
Ajax updatepanel contains property called UpdateMode this property is used to specify whether UpdatePanel is always refreshed during a partial render or if it refresh only when a particular trigger hit. By default updatepanel contains UpdateMode="Always" if we want to set it conditionally we need to change this property UpdateMode="Conditional"
Ajax updatepanel control contains two child tags those are ContentTemplate and Triggers.
ContentTemplate is used to hold the content of the page means suppose we designed page with some controls we will place controls inside of the ContentTemplate
Triggers we used in a situation like need to refresh updatepanel only whenever I click some button control in that situation I will define those controls with this Triggers child tag.
Our Sample update panel control will be like this
<asp:UpdatePanel ID="UpdatePanel2" runat="server"
 UpdateMode="Conditional">
 <ContentTemplate>
 <asp:Label ID="Label2" runat="server"
 ForeColor="red" />
……………………………………………………..
………………………………………………………
……………………………………………………….
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="Button1"
 EventName="Click" />
</Triggers>
 </asp:UpdatePanel>
Now we will create one sample application with updatepanels for that first create application and design your aspx page will be likes this
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head id="Head1" runat="server">
 <title>UpdatePanel Example in asp.net</title>
 </head>
 <body>
 <form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server"/>
 <div>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <fieldset style="width:30%">
 <legend>Update Panel-1</legend>
 <asp:Label ID="lbl1" runat="server" ForeColor="green"/><br />
 <asp:Button ID="btnUpdate1" runat="server" Text="Update Both Panels" OnClick="btnUpdate1_Click" />
 <asp:Button ID="btnUpdate2" runat="server" Text="Update This Panel" OnClick="btnUpdate2_Click" />
 </fieldset>
 </ContentTemplate>
 </asp:UpdatePanel>
 <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
 <ContentTemplate>
 <fieldset style="width:30%">
 <legend>Update Panel-2</legend>
  <asp:Label ID="lbl2" runat="server" ForeColor="red" />
  </fieldset>
 </ContentTemplate>
 <Triggers>
 <asp:AsyncPostBackTrigger ControlID="btnUpdate1" EventName="Click" />
 </Triggers>
 </asp:UpdatePanel>
 </div>
 </form>
 </body>
</html>
If you observe above code in UpdatePanel2 I defined Triggers property with btnUpdate1. Here UpdatePanel2 content will update only whenever we click on btnUpdate1 because we defined UpdatePanel2 property UpdateMode="Conditional" and we set AsyncPostBackTrigger property with btnUpdate1
Write following code in code behind
C#.NET
protected void btnUpdate1_Click(object sender, EventArgs e)
{
lbl1.Text = DateTime.Now.ToLongTimeString();
lbl2.Text = DateTime.Now.ToLongTimeString();
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
lbl1.Text = DateTime.Now.ToLongTimeString();
lbl2.Text = DateTime.Now.ToLongTimeString();
}
VB Code
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnUpdate1_Click(ByVal sender As Object, ByVal e As EventArgs)
lbl1.Text = DateTime.Now.ToLongTimeString()
lbl2.Text = DateTime.Now.ToLongTimeString()
End Sub
Protected Sub btnUpdate2_Click(ByVal sender As Object, ByVal e As EventArgs)
lbl1.Text = DateTime.Now.ToLongTimeString()
lbl2.Text = DateTime.Now.ToLongTimeString()
End Sub


DEMO




This article provides detailed information on how to send Email using C# in a step by step procedure. Although there are many articles on the web providing the same info, many of them left out some interesting concepts untouched. Concepts like Alternate Views, Linked Resources add an additional fragrance to the world of Email in C#.
Out of my experience in the fascinating world of ASP.NET and C#, it’s been observed that many of the new programmers often run into lot of doubtful scenarios while performing an Email assignment. The thought of helping new comers is my prior motivation which made me to write this article.

Step By Step Procedure:

Step 1:


Create a new project in Microsoft Visual Studio 2008 (File -> New -> Project -> Visual C# -> Console Application)
Give an appropriate name (in this case ‘SendEmail’) and also specify the location where to store the project. Leave remaining options untouched.
This step created a console application, where we can create the classes we want and execute them from the command prompt.


Step 2:


Now add a new item to the project we just created (Project -> Add New Item -> Class).
Specify a name to the class (here it is ‘Email’). The code now looks like as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SendEmail
{
    class Email
    {
    }
}
 
This completes the basic setup of the project. Now we will see what are the namespaces required to send an email.                                         

                                                                                                                              
Step 3:


Import the below namespaces – (just type them after ‘using System.Text’)
using System.Net.Mail;
using System.Net.Mime;
System.Net.Mail – by importing this namespace we can use the inbuilt classes like SmtpClient, MailMessage, MailAddress in our code, which are the important classes required to send email.
System.Net.Mime – by importing this we can send email using Multipurpose Internet Mail Extensions like by specifying attachments like pdf’s, sending images in the body of email etc.
Add the Main thread to the class. So at the end of the section the code should be as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmail
{
    class Email
    {
        public static void Main(string[] args)
        {
        }
    }
}

Step 4:

 

Now comes the important coding to accomplish email task. For the sake of understanding the process, the complete code is divided into five blocks.
Block 1:
Create objects of MailMessage and SmtpClient –
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
MailMessage helps us to create the mail and SmtpClient allows us to send mail to the reciepient.

Block 2:


NOTE: the following code is configured to send mails from GMAIL account, later we can configure it as per our requirement.

Add – From, To, CC, BCC, subject, Body – as shown.
m.From = new MailAddress("from@gmail.com", "Display name");
m.To.Add(new MailAddress("to@domain.com", "Display name To"));
m.CC.Add(new MailAddress("CC@yahoo.com", "Display name CC"));
//similarly BCC
m.Subject = "Test";
m.Body = "This is a Test Mail";

MailMessage also provides provision to include options like Priority (sets priority of mail), DeliveryNotificationOptions(instructs SMTP server to send a message to FROM address in case of delay, fail or success mail departure), ReplyTo (email address to which replies will be sent).

Block 3:

Add attachments to the mail using MailMessage.Attachments – To add attachments using file stream, we got to import System.IO namespace.
FileStream fs = new FileStream("E:\\TestFolder\\test.pdf", FileMode.Open, FileAccess.Read);
Attachment a = new Attachment(fs, "test.pdf", MediaTypeNames.Application.Octet);
m.Attachments.Add(a);
We can send multi-media type attachment as shown above or else a simple attachment can be send as follows.
m.Attachments.Add(new Attachment("E:\\windows\\win32.ini"));

Block 4:

This block tells us how to send HTML emails. To send an Html mail we must first make MailMessage.IsBodyHtml to true and to send any images in the mail, we got to use AlternateView and LinkedResource concepts. The code goes as below.
 
string str = "<html><body><h1>Picture</h1><br/><img src=\"cid:image1\"></body></html>";
AlternateView av = AlternateView.CreateAlternateViewFromString(str,null,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg", MediaTypeNames.Image.Jpeg);
lr.ContentId = "image1";
av.LinkedResources.Add(lr);
m.AlternateViews.Add(av);

To reference images attached as linked sources from your Html message body, use cid:contentID in the image tag. And then specify the same name for the LinkedResource.ContentID.

Block 5:

Final block comes with the SMTP credentials (credentials of SMTP server which is responsible to send the message to the recipient).
 
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new System.Net.NetworkCredential("from@gmail.com", "password of from");
sc.EnableSsl = true; // runtime encrypt the SMTP communications using SSL
sc.Send(m);

The other way around maintaining SMTP credentials for a web application is to use Web.Config file. Add the following code in the configuration section of Web.Config file.
 
<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="from@gmail.com">
        <network defaultCredentials="true" host="smtp.gmail.com" port="587"
                 userName="from@gmail.com" password="passworf of from"/>
      </smtp>
    </mailSettings>
  </system.net>

And now there is no need to define smtp credentials every time and everywhere in the web application. And this completes the email assignment.

Important Point:

1) Always use TRY…CATCH block to catch the exceptions, because dealing with SMTP might results in lot of exceptions. Some of the exceptions are SmtpException (when user is not valid), InvalidOperationException (server hostname not defined), SmtpFailedRecipientException etc.
2) The complete example dealt with smtp.gmail.com credentials, in case to send email from different domain use corresponding domain credentials.




Final Code:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmail
{
    class Email
    {
        public static void Main(string[] args)
        {
                   MailMessage m = new MailMessage();
                   SmtpClient sc = new SmtpClient();

            try
            {
                m.From = new MailAddress("from@gmail.com", "Display name");
                m.To.Add(new MailAddress("to@domain.com", "Display name To"));
                m.CC.Add(new MailAddress("CC@yahoo.com", "Display name CC"));
                //similarly BCC
                m.Subject = "Test1";
              m.IsBodyHtml = true;
              m.Body = " This is a Test Mail";

                FileStream fs = new FileStream("E:\\TestFolder\\test.pdf",
                                   FileMode.Open, FileAccess.Read);
                Attachment a = new Attachment(fs, "test.pdf",
                                   MediaTypeNames.Application.Octet);
                m.Attachments.Add(a);

                string str = "<html><body><h1>Picture</h1><br/><img
                                 src=\"cid:image1\"></body></html>";
                AlternateView av =
                             AlternateView.CreateAlternateViewFromString(str,
                             null,MediaTypeNames.Text.Html);
                LinkedResource lr = new LinkedResource("E:\\Photos\\hello.jpg",
                             MediaTypeNames.Image.Jpeg);
                lr.ContentId = "image1";
                av.LinkedResources.Add(lr);
                m.AlternateViews.Add(av);

                sc.Host = "smtp.gmail.com";
                sc.Port = 587;
                sc.Credentials = new
                  System.Net.NetworkCredential(“from@gmail.com","Password");
                sc.EnableSsl = true;
                sc.Send(m);

                Console.ReadLine();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}
 
 
Conclusion:
Concepts behind – “How to send email using C#” are discussed thoroughly and successfully implemented. Sending and Html email with Alternate Views and Linked Resources is discussed. Configuring SMTP server credentials is shown in code.

COUNTASPX.CS

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DataBase.connect);
        DataSet ds = new DataSet();
        string sql = "select Hostel from Stud_Info where Hostel = 'Charlie' ";
        try
        {
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
            adapter.Fill(ds);
            Label3.Text = " Strength " + ds.Tables[0].Rows.Count.ToString();
            con.Close();
        }
        catch (Exception ex)
        {
            Label3.Text = "Error in execution " + ex.ToString();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DataBase.connect);
        DataSet ds = new DataSet();
        string sql = "select Hostel from Stud_Info where Hostel = 'Alpha' ";
        try
        {
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
            adapter.Fill(ds);
            Label1.Text = " Strength " + ds.Tables[0].Rows.Count.ToString();
            con.Close();
        }
        catch (Exception ex)
        {
            Label1.Text = "Error in execution " + ex.ToString();
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DataBase.connect);
        DataSet ds = new DataSet();
        string sql = "select Hostel from Stud_Info where Hostel = 'Bravo' ";
        try
        {
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
            adapter.Fill(ds);
            Label2.Text = " Strength " + ds.Tables[0].Rows.Count.ToString();
            con.Close();
        }
        catch (Exception ex)
        {
            Label2.Text = "Error in execution " + ex.ToString();
        }
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DataBase.connect);
        DataSet ds = new DataSet();
        string sql = "select Hostel from Stud_Info where Hostel = 'Delta' ";
        try
        {
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
            adapter.Fill(ds);
            Label4.Text = " Strength " + ds.Tables[0].Rows.Count.ToString();
            con.Close();
        }
        catch (Exception ex)
        {
            Label4.Text = "Error in execution " + ex.ToString();
        }
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(DataBase.connect);
        DataSet ds = new DataSet();
        string sql = "select Hostel from Stud_Info  ";
        try
        {
            con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
            adapter.Fill(ds);
            Label5.Text = " Total Strength " + ds.Tables[0].Rows.Count.ToString();
            con.Close();
        }
        catch (Exception ex)
        {
            Label5.Text = "Error in execution " + ex.ToString();
        }
    }
}





this will count the total number strength of dropdownlist as well as individual strength of 4 different element of dropdonlist
  1 ALPHA
2  BRAVO
3  CHARLIE
 4  DELTA 

HOW TO DISPLAY CLOCK IN ASP.NET

March 12, 2013 |

STEP 1

DRAG SCRIPT MANAGER ON YOUR PAGE

STEP 2

DRAG AND DROP TIMER ON YOUR ASP.NET PAGE


STEP 3

NOW DRAG A LABLE ON YOUR ASP.NET PAGE

SET ID OF LABLE  :  "  lblDateToday"




NOW

lblDateToday.Text = System.DateTime.Now.ToShortDateString();

now put this in the timer event


  public void TimerTime_Tick1(object sender, EventArgs e)
    {
        lblTime.Text = System.DateTime.Now.ToLongTimeString();
    }

First of all declare :

STEP :1

object parameterValue;

then

if (!dr.IsNull("Exit_Date"))
        {
            parameterValue = ((DateTime)dr["Exit_Date"]).ToShortDateString();
        }
        else
        {
            parameterValue = DBNull.Value;
        }



this will insert null value in database at datetime field if no value is entered



 object parameterValue;
 if (!dr.IsNull("Exit_Date"))
        {
            parameterValue = ((DateTime)dr["Exit_Date"]).ToShortDateString();
        }
        else
        {
            parameterValue = DBNull.Value;
        }