Thursday, November 14, 2013

How to know which control has raised a postback?


public string GetPostBackControl(System.Web.UI.Page page)
    {
        Control ctrl1 = null;
        Control ctrl2 = null;
        string ctrlName = page.Request.Params["__EVENTTARGET"];
        string ctrlStr = string.Empty;
        if (ctrlName != null && ctrlName != String.Empty)
        {
            ctrl1 = page.FindControl(ctrlName);
        }
        else
        {
            foreach (string ctl in page.Request.Form)
            {
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    ctrlStr = ctl.Substring(0, ctl.Length - 2);
                    ctrl2 = page.FindControl(ctrlStr);
                }
                else
                {
                    ctrl2 = page.FindControl(ctl);
                }
                if (ctrl2 is System.Web.UI.WebControls.Button || ctrl2 is System.Web.UI.WebControls.ImageButton)
                {
                    ctrl1 = ctrl2;
                    break;
                }
            }
        }

        return ctrl1.ClientID;
    }

Wednesday, March 27, 2013

FileUpload control in asp.net

I have given a example below how to upload file using asp.net FileUpload control.
follow the instruction
1. Drag a file upload control and one button in source code
2. Drag a image control to show the uploaded image
3.Create a folder  name it img
<form id="form1" runat="server">
    <div>
   
        <asp:FileUpload ID="FileUploadControl" runat="server" />
        <asp:Button ID="btnUpload"
            runat="server" Text="Upload" onclick="btnUpload_Click" />
        <br />
        <br />
        <asp:Image ID="Myimage" runat="server" />
    </div>
    </form>
4. copy the code behind below at your button click event

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUploadControl.HasFile)
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            FileUploadControl.SaveAs(Server.MapPath("~/img/")+filename);
            Myimage.ImageUrl = "~/img/" + filename;
        }
    }