Archive

Archive for July, 2010

Disable Button after one Click to prevent Click Twice

July 31, 2010 3 comments

Hi all,

In previous posts i show how to disable button after one click to prevent multiple click

Disable a Button When Clicked once on an ASP.NET Page Containing Validation Controls

Disable a button after single click

Disable button onclientclick twice ASP.Net

now try this way to disable Button after one click :-

add this Javascript Code :-


<script language="javascript" type="text/javascript">
    function disableButton(sender,group)
    {
        Page_ClientValidate(group);
        if (Page_IsValid)
        {
            sender.disabled = "disabled";
            __doPostBack(sender.name, '');
        }
    }
</script>

and in Html

<div>
      Enter Name :-
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
          ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator><br />
    <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" OnClientClick="disableButton(this,'')" UseSubmitBehavior="false" />
   </div>

If there is Validation Group it will be like this :-

Add this Javascript code :-

<script language="javascript" type="text/javascript">
    function disableButton(sender,group)
    {
        Page_ClientValidate(group);
        if (Page_IsValid)
        {
            sender.disabled = "disabled";
            __doPostBack(sender.name, '');
        }
    }
</script>

and HTML will be :-

<div>
      Enter Name :-
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ValidationGroup="i"
          ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>&nbsp;<br />
    <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" OnClientClick="disableButton(this,'i')" UseSubmitBehavior="false" ValidationGroup="i" />
   </div>

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

Use JQuery with FileUpload

July 27, 2010 Leave a comment

Hi

try this example to use JQuery with FileUpload

Step1 :- Open Visual Studio 2008 and Create new website

Step2 :- Download the following  jQuery 1.3.2 , jQuery VS 2008 Doc and the Multiple File Upload PlugIn and Create a “Scripts” folder in the Solution Explorer of your project

Step3 :- Add web page and add this script in the <head> section of your page as shown below

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
      <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>

 Step4 :- From ToolBox drag and drop an ASP.NET FileUpload control and Button Control  and Lable Control to the page.

<asp:FileUpload ID="FileUpload1" runat="server" accept="gif|jpeg|bmp|png|jpg" maxlength="5" />
   <br />
   <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" />
   <br />
   <asp:Label ID="lblMsg" runat="server" Text="">

 Step5 :- In Code behind add the following code


protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            string SavePath, Msg = null;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
                        + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    hpf.SaveAs(Server.MapPath(SavePath));
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                }
            }
            lblMsg.Text = Msg + " Uploaded Successfully.";
        }
    }

    private string GetFileExtension(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Extension;
    }
  
    private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;
        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        chars = a.ToCharArray();
        int size = maxSize;
        byte[] data = new byte[1];
        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }
        return result.ToString();
    }

    private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

    private bool ServerSideValidation()
    {
        string errorMsg = string.Empty, temp = null;
        bool errorFlag = true;
        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if (temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }
        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

    private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.
        if (!IsValidFile(myFile.FileName))
        {
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

    private bool IsValidFile(string filePath)
    {
        bool isValid = false;
        string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.ToUpper().Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }

and don’t forget to use the following NameSpaces

using System.Security.Cryptography; 
using System.Text; 
using System.IO;

Hope this helps

Good Luck.

Categories: ASP.Net, Jquery

Show and Hide Panel with Gridview

July 4, 2010 2 comments

Hi

try this example to Show and Hide Panel with Gridview using Javascript

Step1 :- Open MS VS2005 and create a new Web Site Project

Step2 :- Add new Web Page and Drag Gridview Control from Toolbox and Bind it using SqlDataSource With Northwind Database to Categories Table so your Page will be like this


<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            AutoGenerateColumns="False" CellPadding="4" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ForeColor="#333333"
            onrowdatabound="GridView1_RowDataBound">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:TemplateField>
                <ItemTemplate>
                    <table style="width: 423px; height: 99px">
                        <tr>
                            <td style="width: 49px; height: 52px" valign="top">
                                <asp:Image ID="imgPP" runat="server" ImageUrl="~/title_16.png" />
                            </td>
                            <td colspan="2" style="width: 581px; height: 52px" valign="top">
                                Category ID :- <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Underline="False" Text='<%# Bind("CategoryID") %>'></asp:Label>
                                <br />
                                <asp:Label ID="postlbl" runat="server" ForeColor="#C00000" Text="Category Name :- " Font-Size="Small"></asp:Label>
                                <asp:Label ID="datetime" runat="server" ForeColor="#C00000" Text='<%# Bind("CategoryName") %>'
                                    Font-Size="Small"></asp:Label>
                                <asp:HyperLink ID="hl_StatusComment" runat="server" Font-Size="Smaller" ForeColor="Maroon">View Details</asp:HyperLink>   
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 49px; height: 52px" valign="top">
                            </td>
                            <td colspan="2" style="width: 581px; height: 52px" valign="top">
                                <asp:Panel ID="StatusPanel" Style="visibility:hidden; " runat="server" Width="310px" BorderColor="Gray" BorderWidth="2">
                                    <asp:Label ID="lbl_Description" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                                     <br /><br />
                                    <asp:Button ID="btnClose" runat="server" Text="Close"  />
                                </asp:Panel>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="3" rowspan="2">
                            </td>
                        </tr>
                        <tr>
                        </tr>
                    </table>
                </ItemTemplate>
                </asp:TemplateField>

            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT * FROM [Categories]">
        </asp:SqlDataSource>

Step3 :- Add the following Javascript


<script language="javascript" type="text/javascript">
        function fnShowSearch(obj)
        {
            document.getElementById(obj).style.visibility='visible';             
        }
        function fnHideSearch(obj)
        {
            document.getElementById(obj).style.visibility='hidden';
        }

    </script>

Step4 :- In Code behind add the following code

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btnClose = e.Row.FindControl("btnClose") as Button;
            Panel pnl = e.Row.FindControl("StatusPanel") as Panel;
            HyperLink hl = (HyperLink)e.Row.FindControl("hl_StatusComment");
            if (hl != null && pnl != null && btnClose != null)
            {
                btnClose.Attributes.Add("onclick", " fnHideSearch('" + pnl.ClientID + "'); return false;");
                hl.Attributes.Add("onclick", "fnShowSearch('" + pnl.ClientID + "'); return false;");
            }
        }
    }

Step5 :- Add new Web.Config and add the connection String

<connectionStrings>
  <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Hope this helps

Good Luck 🙂

Categories: ASP.Net, Javascript