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";
   

  }
}