Creating javascript alerts in ASP.NET with UpdatePanel

creating an alert when you are using an UpdatePanel is slightly different, but simpler than you might think - you just need to make sure the System.Type is the UpdatePanel type, and use the ScriptManager rather than the ClientScript like so
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdatePanel.aspx.cs" Inherits="UpdatePanel" %>

<!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">
      <asp:ScriptManager ID="scriptMangerTest" runat="Server">
      </asp:ScriptManager>
      <asp:UpdatePanel ID="updateTest" runat="Server">
          <ContentTemplate>
              <div>
                  <table cellpadding="0" cellspacing="0" width="60%">
                      <tr>
                          <td align="right">
                              <asp:Label ID="lblName" runat="Server" Text="Enter E-mail Id">
           
                              </asp:Label>
                          </td>
                          <td>
                              <asp:TextBox ID="txtEmail" runat="Server"></asp:TextBox>
                          </td>
                      </tr>
                      <tr>
                          <td colspan="2" align="left">
                              <asp:Button ID="btnCheck" runat="Server" Text="Validate" OnClick="btnCheck_Click" />
                          </td>
                      </tr>
                  </table>
              </div>
          </ContentTemplate>
      </asp:UpdatePanel>
  </form>
</body>
</html>
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 UpdatePanel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCheck_Click(object sender, EventArgs e)
    {
        if (!CheckEmail(txtEmail.Text))
        {

            Guid gMessage = Guid.NewGuid();
            string sMessage = "alert('Invalid E-mail Id ');";

            ScriptManager.RegisterStartupScript(updateTest, updateTest.GetType(), gMessage.ToString(), sMessage, true);
        }

    }

    private bool CheckEmail(string EmailAddress)
    {
        string strPattern = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";

        if (System.Text.RegularExpressions.Regex.IsMatch(EmailAddress, strPattern))

        { return true; }

        return false;


    }
}

ASP.net TreeView Tips and Trics

In this Post i will show
  1. How to Automatically check all ChildNode CheckBoxes on Checking ParentNode CheckBox using JavaScript
  2. How to get checked value from treeview
  3. How To open Treeview in ModalPopupExtender control
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!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 id="Head1" runat="server">
   <title>Untitled Page</title>
   <style type="text/css">
       .modalBackground {
           background-color:Gray;
           filter:alpha(opacity=70);
           opacity:0.7;
       }

       .modalPopup {
           background-color:#FFD9D5;
           border-width:3px;
           border-style:solid;
           border-color:Gray;
           padding:3px;
           width:250px;
       }
   </style>
</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager ID="ScriptManager1" runat="server">
       </asp:ScriptManager>
       <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" Style="display: none">
           <asp:UpdatePanel ID="UpdatePanel1" runat="server">
               <ContentTemplate>
                   <asp:TreeView ID="TestTreeView" runat="server" onclick="SelectAllChildNodes();" OnSelectedNodeChanged="TestTreeView_SelectedNodeChanged"
                       ShowCheckBoxes="All" >
                       <Nodes>
                           <asp:TreeNode Text="My Computer" Value="My Computer">
                               <asp:TreeNode Text="Favorites" Value="Favorites">
                                   <asp:TreeNode Text="News" Value="News">
                                       <asp:TreeNode Text="MSN" Value="MSN" />
                                       <asp:TreeNode Text="MSNBC News" Value="MSNBC News" />
                                   </asp:TreeNode>
                                   <asp:TreeNode Text="Technology" Value="Technology">
                                       <asp:TreeNode Text="Microsoft" Value="Microsoft" />
                                       <asp:TreeNode Text="ASP.NET" Value="ASP.NET" />
                                       <asp:TreeNode Text="GotDotNet" Value="GotDotNet" />
                                       <asp:TreeNode Text="MSDN" Value="MSDN" />
                                   </asp:TreeNode>
                                   <asp:TreeNode Text="Shopping" Value="Shopping">
                                       <asp:TreeNode Text="MSN Shopping" Value="MSN Shopping" />
                                       <asp:TreeNode Text="MSN Autos" Value="MSN Autos" />
                                   </asp:TreeNode>
                               </asp:TreeNode>
                               <asp:TreeNode Text="City Links" Value="City Links">
                                   <asp:TreeNode Text="MapPoint" Value="MapPoint" />
                                   <asp:TreeNode Text="MSN City Guides" Value="MSN City Guides" />
                               </asp:TreeNode>
                               <asp:TreeNode Text="Music Links" Value="Music Links">
                                   <asp:TreeNode Text="MSN Music" Value="MSN Music" />
                               </asp:TreeNode>
                           </asp:TreeNode>
                       </Nodes>
                   </asp:TreeView>
                   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
               </ContentTemplate>
           </asp:UpdatePanel>
           <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
           <asp:Button ID="btnSend" runat="Server" Text="Send" OnClick="btnSend_Click" />
       </asp:Panel>
       <asp:Button ID="btnOpen" runat="server" Text="Open" />
       <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" BehaviorID="myMPE1" runat="server"
           TargetControlID="btnOpen" PopupControlID="Panel1" CancelControlID="btnCancel"
           BackgroundCssClass="modalBackground">
       </ajaxToolkit:ModalPopupExtender>

       <script type="text/javascript" language="javascript">
           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
           function EndRequestHandler(sender, args){
               alert($get("<%=TextBox1.ClientID %>").value);
               $find("myMPE1").hide();
           }
       </script>

       <asp:GridView ID="A" runat="Server">
           <Columns>
           </Columns>
       </asp:GridView>

       <script type="text/javascript" language="javascript">
   function SelectAllChildNodes()
   {
       //debugger;
       var obj = window.event.srcElement;
       var treeNodeFound = false;

       var checkedState;
       if (obj.tagName == "INPUT" && obj.type == "checkbox")
       {
           var treeNode = obj;
           checkedState = treeNode.checked;
           do
           {
               obj = obj.parentElement;
           } while (obj.tagName != "TABLE")
         
           var parentTreeLevel = obj.rows[0].cells.length;          
           var parentTreeNode = obj.rows[0].cells[0];
           var tables = obj.parentElement.getElementsByTagName("TABLE");
           var numTables = tables.length;
           if (numTables >= 1)
           {
               for (iCount=0; iCount < numTables; iCount++)
               {
                   if (tables[iCount] == obj)
                   {
                       treeNodeFound = true;
                       iCount++;
                       if (iCount == numTables)
                       {
                           return;
                       }
                   }
                   if (treeNodeFound == true)
                   {
                       var childTreeLevel = tables[iCount].rows[0].cells.length;
                       if (childTreeLevel > parentTreeLevel)
                       {
                           var cell = tables[iCount].rows[0].cells[childTreeLevel - 1];
                           var inputs = cell.getElementsByTagName("INPUT");
                           inputs[0].checked = checkedState;
                       }
                       else
                       {
                           return;
                       }
                   }
               }
           }
       }
   }
       </script>

   </form>
</body>
</html>
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.Collections.Generic;
public partial class Test : System.Web.UI.Page
{

    string nodelist = "";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        ArrayList arr = new ArrayList();
        arr.Add(GetCheckedNodes());
        A.DataSource = arr;
        A.DataBind();
    }
    protected void TestTreeView_SelectedNodeChanged(object sender, EventArgs e)
    {
        TextBox1.Text = TestTreeView.SelectedNode.Text;
    }
  
    public string GetCheckedNodes()
    {

        foreach (TreeNode node in TestTreeView.Nodes)
        {
            nodelist += FindCheckedNodes(node, ref nodelist);
        }
        return nodelist;
    }

    private string FindCheckedNodes(TreeNode node, ref string nodelist)
    {
        if (node.Checked == true) nodelist += node.Text + ',';
        foreach (TreeNode childNode in node.ChildNodes)
        {
            FindCheckedNodes(childNode, ref nodelist);
        }
        return nodelist;
    }


}

How to make your ASP.Net label multilin

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

<!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="lblMultiline" runat="Server" Text=""></asp:Label>
       </div>
   </form>
</body>
</html>

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 Multiline : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        lblMultiline.Text = FormatText("aspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebookaspdotnetcodebook");

    }
    public string FormatText(string sText)
    {

        int start = 0;
        int length = 40;
        int parts = sText.Length / length + 1;

        string strPart = "";
        while (start < sText.Length)
        {
            int charactersToGet = start + length < sText.Length ? length : sText.Length - start;
            strPart = strPart + sText.Substring(start, charactersToGet) + "</br>";
            start += length;
        }
        return strPart;

    }
}

How To Create TextBox Control Dynamically at Runtime

http://aspdotnetcodebook.blogspot.com/2008/03/how-to-create-textbox-control.html in this post i will show how to create Textbox Control dynamically and read there value.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextBoxDynamic.aspx.cs" Inherits="TextBoxDynamic" %>

<!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>
           <table width="100%" cellpadding="0" cellspacing="0">
               <tr>
                   <td colspan="2">
                       <asp:PlaceHolder ID="phTextBoxes" runat="Server"></asp:PlaceHolder>
                   </td>
               </tr>
               <tr>
                   <td>
                       <asp:Button ID="btnAddTitle" runat="Server" Text="Add" />
                   </td>
                   <td>
                       <asp:Button ID="btnRead" runat="Server" Text="Read" OnClick="btnRead_Click" />
                   </td>
               </tr>
           </table>
       </div>
   </form>
</body>
</html>
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 TextBoxDynamic : System.Web.UI.Page
{
   
    string strValue = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void CreateTextBoxes()
    {

        for (int counter = 0; counter <= NumberOfControls; counter++)
        {
            TextBox tb = new TextBox();
            tb.Width = 150;
            tb.Height = 18;
            tb.TextMode = TextBoxMode.SingleLine;
            tb.ID = "TextBoxID" + (counter + 1).ToString();
            // add some dummy data to textboxes
            tb.Text = "Enter Title " + counter;
            phTextBoxes.Controls.Add(tb);
            phTextBoxes.Controls.Add(new LiteralControl("<br/>"));

        }

    }
    protected override void CreateChildControls()
    {
        // Here we are recreating controls to persist the ViewState on every post back
        if (Page.IsPostBack)
        {
            NumberOfControls += 1;
            CreateTextBoxes();
        }
        else
        {
            CreateTextBoxes();
            // Increase the control value to 1
            NumberOfControls = 0;
        }

    }
    protected void btnAddTitle_Click(object sender, EventArgs e)
    {


        NumberOfControls += 1;


    }
    public int NumberOfControls
    {
        get
        {
            if (ViewState["Count"] == null)
            {
                return 0;
            }
            return (int)ViewState["Count"];
        }
        set
        {
            ViewState["Count"] = value++;
        }
    }

    private void ReadTextBoxes()
    {
        strValue = string.Empty;
        int n = NumberOfControls;

        for (int i = 0; i <= NumberOfControls; i++)
        {

            string boxName = "TextBoxID" + (i + 1).ToString();
            TextBox tb = phTextBoxes.FindControl(boxName) as TextBox;
            strValue += tb.Text + "\n";
          



        }
        Response.Write(strValue);


    }


    protected void btnRead_Click(object sender, EventArgs e)
    {
        ReadTextBoxes();


    }
}

How To Use RegularExpressionValidator with FileUpload control

In this post i will show how to use RegularExpressionValidator to check to make sure the file is a .doc, or .txt extension.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadTest.aspx.cs" Inherits="FileUploadTest" %>

<!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>
           <table cellpadding="0" cellspacing="0" width="100%">
               <tr>
                   <td>
                       Select File</td>
                   <td>
                       <asp:FileUpload ID="fileUpload" runat="Server" /></td>
                   <td>
                       <td align="left">
                           <asp:RegularExpressionValidator runat="server" ID="valUpTest" ControlToValidate="fileUpload"
                               ErrorMessage="Image Files Only (.doc, .txt, .rtf)" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.rtf)$" />
                       </td>
                   </td>
               </tr>
               <tr>
                   <td colspan="2" align="Center">
                       <asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="btnSubmit_Click" />
                   </td>
               </tr>
           </table>
       </div>
   </form>
</body>
</html>
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.IO;

public partial class FileUploadTest : System.Web.UI.Page
{
   string sPath = "Image";
   protected void Page_Load(object sender, EventArgs e)
   {

   }
   protected void btnSubmit_Click(object sender, EventArgs e)
   {
       if (fileUpload.HasFile)
       {


           fileUpload.PostedFile.SaveAs(Server.MapPath(sPath) + "/" + Path.GetFileName(fileUpload.PostedFile.FileName));

       }
   }
}

How To Add Multiple UserControls using RequiredFieldValidators that work independently

The trick is to make the Validation Group name in each user control unique. Since its a single user control used in both places, you have to make it unique programmatically. Do this in Page_Load of the user control:

Assign the value of the UniqueID property of the UserControl to each ValidationGroup property on the UserControl. Something like this:

public string ValidationGroup
 {
     get
     {
         if (ViewState["VALGROUP"] == null)
             return this.ClientID;
         else return (string)ViewState["VALGROUP"];
     }
     set
     {
         ViewState["VALGROUP"] = this.ClientID;
     }
 }
Create an UserControl Test.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Test.ascx.cs" Inherits="Test" %>
<asp:TextBox ID="txt1" runat="Server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" runat="Server" ErrorMessage="(Require)" ControlToValidate="txt1"></asp:RequiredFieldValidator>
<asp:Button ID="btnAdd" runat="server" Text="Add" />
Add Multiple Instance of UserControl on test page.

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

<%@ Register Src="Test.ascx" TagName="Test" TagPrefix="uc1" %>
<!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>
          &nbsp; &nbsp;
          <table style="width: 100%">
              <tr>
                  <td style="width: 100px">
                      <uc1:Test ID="Test1" runat="server" />
                  </td>
                  <td style="width: 100px">
                      <uc1:Test ID="Test3" runat="server"></uc1:Test>
                  </td>
              </tr>
              <tr>
                  <td style="width: 100px">
                      <uc1:Test ID="Test2" runat="server" />
                  </td>
                  <td style="width: 100px">
                      <uc1:Test ID="Test4" runat="server" />
                  </td>
              </tr>
          </table>
      </div>
  </form>
</body>
</html>

How To Make Clickable image

The Image Web server control is used to display an image on a Web page. To set the image to be displayed for this control we use the ImageUrl property.In this post i will show how to make Clickable image .(Unfortunately image control not supports NavigateUrl )

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager ID="ScriptManager1" runat="server" />
       <div>
           <a id="link1" runat="Server">
               <asp:Image ID="SlideShowImage1" CssClass="crop" runat="server" Width="630px" Height="192px" />
           </a>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      SlideShowImage1.ImageUrl = "sunset.jpg";
      link1.HRef = "http://www.aspdotnetcodebook.blogspot.com";
      link1.CausesValidation = false;
      link1.Target = "_blank";
   

  }
}

SQL XML output to populate a treeview

In this post I will show how to populate an asp.net tree view from the output of sql stored procedure. The table looks like this:

pageid pagename parentid

--- ---------- -------------

1 N1 0

3 N4 1

4 N10 3

5 N7 3

SET ANSI_NULLS ON 
SET QUOTED_IDENTIFIER ON 
GO
ALTER PROCEDURE [DBO].[gentree]
AS
  BEGIN
    SET NOCOUNT ON;
    WITH TREE
         AS (SELECT CAST(1 AS INT) AS LEVEL,
                    PAGEID,
                    PAGENAME,
                    CAST(RIGHT(' '
                                 + CONVERT(VARCHAR(11),PAGEID),11) AS VARCHAR(120)) AS HIERARCHY
             FROM   PAGE
             WHERE  PARENTID = '0'
             UNION ALL
             SELECT LEVEL
                      + 1,
                    B.PAGEID,
                    B.PAGENAME,
                    CAST(A.HIERARCHY
                           + '/'
                           + RIGHT(' '
                                     + CONVERT(VARCHAR(11),B.PAGEID),11) AS VARCHAR(120))
             FROM   TREE A
                    JOIN PAGE B
                      ON A.PAGEID = B.PARENTID),
         SEQTREE
         AS (SELECT LEVEL,
                    Row_number()
                      OVER(ORDER BY HIERARCHY) AS SEQ,
                    PAGEID,
                    PAGENAME,
                    HIERARCHY
             FROM   TREE)
    SELECT '<Root>'
             + REPLACE(REPLACE((SELECT   '`tree id="'
                                           + CONVERT(VARCHAR(11),A.PAGEID)
                                           + '" PageName="'
                                           + A.PAGENAME
                                           + '" ~'
                                           + CASE
                                               WHEN A.LEVEL < Isnull(B.LEVEL,1) THEN ''
                                               ELSE Replicate('`/tree~',1
                                                                          + A.LEVEL
                                                                          - Isnull(B.LEVEL,1))
                                             END
                                FROM     SEQTREE A
                                         LEFT JOIN SEQTREE B
                                           ON A.SEQ
                                                + 1 = B.SEQ
                                ORDER BY A.SEQ
                                for xml path('')
                                                               
                               ),'`','<'),'~','>')
             + '</Root>' AS MYXML
  END
  --exec [GenTree]

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

<!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:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" ExpandDepth="0">
               <DataBindings>
                   <asp:TreeNodeBinding DataMember="tree" TextField="PageName" ValueField="id" />
               </DataBindings>
           </asp:TreeView>
           <asp:XmlDataSource ID="XmlDataSource1" runat="server" OnLoad="XmlDataSource1_Load"
               XPath="Root/tree"></asp:XmlDataSource>
       </div>
   </form>


</body>
</html>

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.Data.SqlClient;

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

   }
   protected void XmlDataSource1_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {

           SqlConnection SqlCon = new SqlConnection("server=(local);database=CMMForStarters;uid=sa;pwd=12345");

           SqlCon.Open();

           SqlCommand SqlCmd = new SqlCommand("GenTree", SqlCon);

           SqlCmd.CommandType = CommandType.StoredProcedure;

           SqlDataReader SqlDrr = SqlCmd.ExecuteReader();

           if (SqlDrr.Read())
           {

               XmlDataSource1.Data = SqlDrr.GetString(0);

           }

           SqlDrr.Close();

           SqlCon.Close();

           SqlCmd.Dispose();

           SqlCon.Dispose();
       }

   }

}

How To Add Session Timeout Popup in asp.net

If you need to alert a user that his session will time out. This is how to do it. Add the following code snippet to the OnInit method on the base page of your application.
protected override void OnInit(EventArgs e)
   {
       base.OnInit(e);
       string script = "window.setTimeout(\"alert('Your session expired!');\", " + (Session.Timeout - 1) * 60000 + ")";
       this.Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionManager", "<script language=\"javascript\">" + script + "</script>");
   }

AdRotator control and Database


The AdRotator control reads advertisement information from a data source, which contains one or more ad records. You can store ad information in a database table with a specific schema, and then use a data source control to read the ad records at run time. If you have an existing table with ad information, you can map the schema of your table to the fields that are required by the AdRotator control.
You can store ad information in any type of database, as long as you have the corresponding data source control for that database.

To create the database table for ads

1. If you do not already have a database table that contains the ad information, create a table with the following schema. All columns except ID are optional.
Data types are provided as SQL Server types. If you are using a different database, substitute the appropriate corresponding type.
Column name
Data type
Description
ID int Primary key. This column can have any name.
ImageUrl nvarchar(length) The relative or absolute URL of the image to display for the ad.
NavigateUrl nvarchar(length) The target URL for the ad. If you do not provide a value, the ad is not a hyperlink.
AlternateText nvarchar(length) The text displayed if the image cannot be found. In some browsers, the text is displayed as a ToolTip. Alternate text is also used for accessibility so that users who cannot see the graphic can hear its description read out loud.
Keyword nvarchar(length) A category for the ad on which the page can filter.
Impressions int(4) A number that indicates the likelihood of how often the ad is displayed. The larger the number, the more often the ad will be displayed. The total of all impressions values in the XML file may not exceed 2,048,000,000 - 1.
Width int(4) The width of the image in pixels.
Height int(4) The height of the image in pixels.
2. If you have an existing database table with ad information in it, set the following properties of the AdRotator control to map your database table schema to the fields required by the control:
3. Insert new records into the table with ad information.



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

<%@ 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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManger1" runat="Server">
    </asp:ScriptManager>
    <div>
        <asp:Timer runat="server" Interval="10000" ID="SlideShowTimer" OnTick="SlideShowTimer_Tick" />
        <asp:UpdatePanel runat="server" ID="SlideShow" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Image runat="Server" ID="SlideShowImage1" ImageUrl="" Width="100%" Height="150px" />
                <asp:AdRotator ID="AdRotator1" runat="Server" />
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="SlideShowTimer" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
        <cc1:UpdatePanelAnimationExtender runat="server" ID="UPextender" TargetControlID="SlideShow"
            BehaviorID="animation">
            <Animations>
      <OnUpdating>
           <%-- It should take 1/2 of a second to fade out --%>
           <FadeOut Duration=".5" Fps="20" minimumOpacity=".1" />
       </OnUpdating>
       <OnUpdated>
           <%-- It should take 1 and 1/2 of a second to fade back in --%>
           <FadeIn Duration="1.5" Fps="20" minimumOpacity=".1" />
       </OnUpdated>
            </Animations>
        </cc1:UpdatePanelAnimationExtender>
    </div>
    </form>
</body>
</html>


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.Data.SqlClient;
public partial class AddRotator : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            AdRotator1.DataSource = FetchAdsFromDB();
            AdRotator1.DataBind();

        }
    }
    protected void SlideShowTimer_Tick(object sender, EventArgs e)
    {
        AdRotator1.DataSource = FetchAdsFromDB();
        AdRotator1.DataBind();

    }
    private DataTable FetchAdsFromDB()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection("Your Connection String");
        SqlDataAdapter da = new SqlDataAdapter("select AlternateText,ImageUrl,NavigateUrl,Impressions  from [add]", con);
        da.Fill(dt);
        return dt;
    }
}

How To Create Slideshow using UpdatePanel and Timer

In this Post i will show how to create Slideshow using UpdatePanel and Timer Control
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager ID="ScriptManager1" runat="server" />
       <div>
           <asp:Timer runat="server" Interval="10000" ID="SlideShowTimer" OnTick="SlideShowTimer_Tick" />
           <br />
           <h2 style="text-transform: uppercase; margin: 10px 0px 0px 8px; display: inline;">
               Welcome to My Photo Gallery
           </h2>
           <br />
           <asp:UpdatePanel runat="server" ID="SlideShow" UpdateMode="Always">
               <ContentTemplate>
                   <%-- This is the main slideshow image control --%>
                   <img runat="server" id="SlideShowImage1" src="~/Images/1.jpg" alt="First Image" />
                   <asp:Label runat="server" ID="SlideShowText" Text="First Slide" />
               </ContentTemplate>
               <Triggers>
                   <%-- The update panel will postback when the timer 'tick' event fires --%>
                   <asp:AsyncPostBackTrigger ControlID="SlideShowTimer" EventName="Tick" />
               </Triggers>
           </asp:UpdatePanel>
           <cc1:UpdatePanelAnimationExtender runat="server" ID="UPextender" TargetControlID="SlideShow"
               BehaviorID="animation">
               <Animations>

      <OnUpdating>

           <%-- It should take 1/2 of a second to fade out --%>

           <FadeOut Duration=".5" Fps="20" minimumOpacity=".1" />

       </OnUpdating>

       <OnUpdated>

           <%-- It should take 1 and 1/2 of a second to fade back in --%>

           <FadeIn Duration="1.5" Fps="20" minimumOpacity=".1" />

       </OnUpdated>

               </Animations>
           </cc1:UpdatePanelAnimationExtender>
       </div>
   </form>
</body>
</html>
• The script manager is required on the page for the AJAX extensions to work correctly. • The timer control raises the "tick" event every 10 seconds. • The Update panel updateMode is set to always. This means that anytime any item on the page raises a postback event, the update panel will update itself. The Update panel also contains an img and label in its content template. There is also a Trigger section that registers the timers "tick" event as a trigger for the update panel to update. • The Update panel animation extender exists to handle the desired fade out / fade in effect. The update panel animation extender section contains animation specific xml. Read the animation reference and walkthrough. My specific animation is set to fade to an opacity of .1 over a period of .5 seconds. And then when it fades back in, it will start at .1 opacity, and take 1.5 seconds to return to full opcaity. SlideShowTimer_Tick event handler: The timer control fires this event every 10 seconds. As you can see, the event handler creates a DateTime stamp 1/2 second from when the event is fired. This is use to create a delay of half a second, so that the update panel animation can finish it's FadeOut animation before we change the image. After the .5 second delay is completed, we get a random image name from the RandomImageName() method. We then set the text of the image caption to be the name of the new image file. RandomImageName() method: This is a private method that returns a string value. We create an instance of the System.Random class. We then limit the random integer to be a number between 1 and 5, since we are only working with 6 images in the slideshow.
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SlideShowTimer_Tick(object sender, EventArgs e)
    {
        DateTime later = DateTime.Now.AddSeconds(.5);
        while (DateTime.Now < later)
        {

        }

        this.SlideShowImage1.Src = RandomImageName();
        this.SlideShowText.Text = this.SlideShowImage1.Src.ToString();

    }
    private string RandomImageName()
    {

        Random rand = new Random();

        int RandomInt = rand.Next(0, 5);

        switch (RandomInt)
        {

            case 0:
                return "~/Images/1.jpg";
                break;
            case 1:
                return "~/Images/2.jpg";
                break;
            case 2:
                return "~/Images/3.jpg";
                break;
            default:
                return "~/Images/1.jpg";
                break;

        }


    }
}