Adsence750x90

Thursday, July 8, 2010

UpdateProgress Control

This sample illustrate how to implement UpdateProgress Control in ASP.Net

UpdatePanel control enable partial page rendering in ASP.Net. using UpdateProgress control enable  status  when Updating UpdatePanel. UpdateProgress have ProgressTemplate, When updates is happen  UpdateProgress show the content in ProgressTemplate.

  <asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
            <ProgressTemplate>
                <div style="color:Red;font-size:xx-large;">Please wait ......</div>
            </ProgressTemplate>
       </asp:UpdateProgress>


AssociatedUpdatePanelID is enable which update is shown update process. Here i am displaying time in label control. When user click update button  status is shown in UpdateProgress control


protected void UpdateTime_Click(object sender, EventArgs e)
    {
         //sleeps for 2 seconds 
        System.Threading.Thread.Sleep(2000);
        lblDate.Text = DateTime.Now.ToString();
    }

Full Source Code



<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
               <asp:ScriptManager ID="ScriptManager1" runat="server">
               </asp:ScriptManager>
               
               <asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
                    <ProgressTemplate>
                        <div style="color:Red;font-size:xx-large;">Please wait ......</div>
                    </ProgressTemplate>
               </asp:UpdateProgress>
                
                <asp:UpdatePanel runat="Server" ID="UpdatePanel1" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:Label ID="lblDate" runat="server"></asp:Label>
                                <asp:Button ID="UpdateTime" runat="server" onclick="UpdateTime_Click" Text="Update" />
                            </ContentTemplate>
                </asp:UpdatePanel>
         </div>
    </form>
</body>
</html>

Server side code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
public partial class Default2 : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblDate.Text = DateTime.Now.ToString();
        }
       
    }
    protected void UpdateTime_Click(object sender, EventArgs e)
    {
        //sleeps for 2 seconds 
        System.Threading.Thread.Sleep(2000);
        lblDate.Text = DateTime.Now.ToString();
    }
}

Output



Download Source

Wednesday, July 7, 2010

How to get Session Variable in Class File

How to get Session Variable in Class (.cs) File 

Normally Session is not accessible in Class file. when  one try to call Session in class file it return "Object reference not set to an instance of an object." error description like " An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code." this error is thrown by System.NullReferenceException. To access Session in class file Microsoft introduce a Interface IRequiresSessionState, derived from System.Web.SessionState



 The metadata of IRequiresSessionState


namespace System.Web.SessionState
{
    // Summary:
    //     Specifies that the target HTTP handler requires read and write access to
    //     session-state values. This is a marker interface and has no methods.
    public interface IRequiresSessionState
    {
    }
}




IRequiresSessionState Specifies that the target HTTP handler requires read and write access to session-state values. IRequiresSessionState has no methods.


How to Use



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
/// 
/// Summary description for GetSessionHelper
/// 
public class SessionHelper : IRequiresSessionState
{
    public SessionHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// 
    /// Get Session values
    /// 
    /// session key    /// object value
    public object GetSession(string key)
    {
        //check session 
        if (HttpContext.Current.Session[key] != null)
        {
            //return session value
            return HttpContext.Current.Session[key];
        }
        else
        {
            //return empty string
            return string.Empty;
        }
    }
}




Calling SessionHelper Class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Creating object of SessionHelper Class
        SessionHelper objSessionHelper = new SessionHelper();
        //setting session value in a variable
        string sessionValue = objSessionHelper.GetSession("test").ToString();
        //writing session value in Page
        Response.Write(sessionValue);
    }
}


Monday, July 5, 2010

Get Value of Dynamically generated TextBox

how to get value of dynamically generated TextBox using javascript


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class placeholderissue : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (TextBox1.Text != string.Empty)
            {
                int count = 0;
                int.TryParse(TextBox1.Text, out count);
                
                for (int i = 0; i < count; i++)
                {
                    TextBox txt = new TextBox();
                    txt.ID = "dynamicText" + i.ToString();
                    if (PlaceHolder1.FindControl(txt.ID) != null)
                    {
                        PlaceHolder1.Controls.Add(txt);
                    }
                }
            }
        }
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text != string.Empty)
        {
            int count=0;
            int.TryParse(TextBox1.Text,out count);
            for (int i = 0; i < count; i++)
            {
                TextBox txt = new TextBox();
                txt.ID = "dynamicText" + i.ToString();
                PlaceHolder1.Controls.Add(txt);
            }
        }
    }
}






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

<!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">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />
        <br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <input id="Button2" type="button" value="button" onclick="GetTextBoxValue();" />
        <script language="javascript">
            function GetTextBoxValue() {
                var count = document.getElementById("TextBox1").value;
                if (count > 0) {
                    for (i = 0; i < count; i++) {
                        alert(document.getElementById("dynamicText" + i).value);
                    }
                }
            }
        </script>
    <div>
    </form>
</body>
</html>




Source Code

Insert Image in to Database

Insert Image in to Database

datatype of image in database is Byte[], so we insert image byte in to Database

FileUploader controls is used to select file, FileUploader control have a property FileBytes it return byte array (byte[]) of image, this Byte[] is stored in dataBase

example


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void ImageUploadToDataBase(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Your Connection string");
        try
        {
            con.Open();
            byte[] imageByte = FileUpload1.FileBytes;
            SqlCommand cmd = new SqlCommand("INSERT INTO table (image,imagename) VALUES (@0,@1))", con);
            object[] cmdParams = new object[2];
            cmdParams[0] = imageByte;
            cmdParams[1] = "Name of Image";
            for (int i = 0; i < cmdParams.Length; i++)
            {
                cmd.Parameters.AddWithValue(i.ToString(), cmdParams[i]);
            }
            cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
        }
        finally { con.Close(); }
       
    }
    
}

Multiple File Upload in ASP.Net

ASP.Net Multiple File Upload

Using HttpFileCollection class provide  to access and manage file uploaded from client. But still have the problem of multiple selection of files. With over limitation am am going to explain multiple  uploading by multiple FileUploader Controls. HttpPostedFile class is used to provide properties and methods if single files in HttpFileCollection class.



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:FileUpload ID="FileUpload2" runat="server" />
    <asp:Button ID="btnUpload" runat="server"
        Text="Upload" onclick="btnUpload_Click" />
    </form>
</body>
</html>





 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class generic : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Post file Collection Class
        HttpFileCollection files = Request.Files;
        if (files.Count > 0)
        {
            for (int i = 0; i < files.Count; i++)
            {
                //read Individual files 
                HttpPostedFile p = files[i];
                string path = Server.MapPath(Guid.NewGuid().ToString() + ".jpg");
                p.SaveAs(path);
            }
        }
    }
}

Friday, July 2, 2010

Dynamically Add AJAX Control Toolkit ValidatorCallout Extender

How to add AJAX Control Toolkit  ValidatorCallout Extender to Dynamic TextBox

To add Ajax Control ToolKit ValidatorCallout we need one TextBox and RequiredFieldValidator. Now i am creating all controls are adding dynamically.  For more information, see  ValidatorCallout control.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Dynamically Creating TextBox
        TextBox txtBox = new TextBox();
        txtBox.ID = "TextBox1";
        txtBox.MaxLength = 100;

        //Dynamically Creating RequiredFieldValidator Control
        RequiredFieldValidator requiredFieldValidater = new RequiredFieldValidator();
        requiredFieldValidater.ID = "RequiredFieldValidator1";
        requiredFieldValidater.ControlToValidate = txtBox.ID;
        requiredFieldValidater.ErrorMessage = "Name is required.";
        requiredFieldValidater.Text = "*";

        //Dynamically Creating ValidatorCalloutExtender Control
        AjaxControlToolkit.ValidatorCalloutExtender validatorCalloutExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
        validatorCalloutExtender.ID = "ValidatorCalloutExtender1";
        validatorCalloutExtender.TargetControlID = requiredFieldValidater.ID;

        //Dynamically Adding controls to PlaceHolder Control
        PlaceHolder1.Controls.Add(txtBox);
        PlaceHolder1.Controls.Add(requiredFieldValidater);
        PlaceHolder1.Controls.Add(validatorCalloutExtender);
    }
}




Output Sample









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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Thursday, July 1, 2010

Creating Dynamic Controls in ASP.Net

Server Side Code
Code snippet for creating Dynamic Controls in ASP.Net. adding dynamic contents and reading the values of dynamically generated controls in ASP.Net have little issue. because after PostBack dynamic controls are disappear from the form. to avoid this we can regenerate controls in page.

This is a simple sample to adding and reading Dynamic controls in ASP.Net.
in !IsPostBack i am create a new instance of ASP TextBox Control.then Adding it to the PlaceHolder Control

if (!IsPostBack)
        {
            //bind textBox in placeholder
            TextBox textBox = new TextBox();
            textBox.ID = "TextBox1";
            PlaceHolder1.Controls.Add(textBox);
        }


in IsPostBack Section

Issue come in this part. after PostBack controls are hidden or disappear from the Form. To avoid this am checking the controls are available in PlaceHolder. if it returns null am binding the controls in PlaceHolder.


//if postback dynamic generated controls are invisible
            //so we can bind in each post back
            TextBox textBox = new TextBox();
            if (PlaceHolder1.FindControl("TextBox1") == null)
            {
                textBox.ID = "TextBox1";
                PlaceHolder1.Controls.Add(textBox);
            }



Reading Values From Generated Control

In this section am explaining how to Read Contents from Dynamically generated TextBox.

i think code is more than effective to explain this, Check the code
I am reading TextBox Value in a Button click.
first check the controls is available in PlaceHolder. if available, display the value using Responce.Write.

TextBox text = PlaceHolder1.FindControl("TextBox1") as TextBox;
        if (text != null)
        {
            Response.Write(text.Text);
        }


Full Source Code


HTML Side

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

<!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">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </div>
    </form>
</body>
</html>




Server Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class dynamiccontrols : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //bind textBox in placeholder
            TextBox textBox = new TextBox();
            textBox.ID = "TextBox1";
            PlaceHolder1.Controls.Add(textBox);
        }
        else
        { 
            //if postback dynamic generated controls are invisible
            //so we can bind in each post back
            TextBox textBox = new TextBox();
            if (PlaceHolder1.FindControl("TextBox1") == null)
            {
                textBox.ID = "TextBox1";
                PlaceHolder1.Controls.Add(textBox);
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox text = PlaceHolder1.FindControl("TextBox1") as TextBox;
        if (text != null)
        {
            Response.Write(text.Text);
        }
    }
}

How to Find Controls in Content Page

How to find content page control in ASP.NET?
ContentPlaceHolder contentPage = Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
        Button button =contentPage.FindControl("Button1") as Button;
        if (button != null)
        {
            button.Text = "Message";
        }