Tuesday, 24 December 2013

Adding controls dynamically and bind events in ASP.NET

In This article we are going to see how to add controls dynamically and bind there events, Now we take a simple scenario Let we upload a image file and add it to the collection, whenever user click the image right side we are going to preview the image.

    <style type="text/css">
    #parent_div_1
    {
    width:1000px;
    height:500px;
    border:1px solid gray;
    margin-left:150px;   
}

#child_div_1{
    float:left;
    width:200px;
    margin-right:5px;
}

#child_div_2{
    float:left;
    width:100px;
    margin-right:5px;
}
</style>



<form id="form1" runat="server">
    <div  align="center">
    <asp:FileUpload ID="fileupload" runat="server" />
    &nbsp;&nbsp;
    <asp:Button ID="upload" runat="server" Text="Upload" onclick="upload_Click" />   
    <br />
    <br />
    </div>
    <div style="margin-left:150px;">
        <div style="float: left; width: 450px; margin:5px;color:Orange">
          Image Collection
        </div>
             <div style="float: left; width: 470px; margin:5px 5px 5px 50px;color:Orange">
          Preview
             </div>
        </div>
   
    <div id="parent_div_1">
        <div style="float: left; width: 450px;height:450px; border:3px dashed blue; margin:5px">
            <asp:Panel ID="panel1" runat="server">
            </asp:Panel>
        </div>
             <div style="float: left; width: 470px;height:450px; border:3px dashed blue; margin:5px 5px 5px 40px">
             <asp:Image ID="image1" runat="server" Height="450" Width="470" />
             </div>
        </div>
    </form>


C#

  protected void Page_Load(object sender, EventArgs e)
        {
            AddFiles();
        }

        protected void upload_Click(object sender, EventArgs e)
        {
            if (fileupload.HasFile)
            {
                fileupload.PostedFile.SaveAs(Server.MapPath("~/Files/" + fileupload.FileName));
                AddFiles();
            }
        }

        private void AddFiles()
        {
            foreach (string filename in System.IO.Directory.GetFiles(Server.MapPath("~/Files/")))
            {
                System.IO.FileInfo file = new System.IO.FileInfo(filename);
                ImageButton img = new ImageButton();
                img.Height = Unit.Pixel(100);
                img.Width = Unit.Pixel(100);
                img.Style.Add("padding", "5px");
                img.ImageUrl = "~/Files/" + file.Name;
                img.Click += new ImageClickEventHandler(img_Click);
                panel1.Controls.Add(img);
            }
        }

        void img_Click(object sender, ImageClickEventArgs e)
        {
            image1.ImageUrl = (sender as ImageButton).ImageUrl;
        }






I Hope this article will help you to learn how to add controls dynamically and bind there events at runtime

No comments:

Post a Comment