In this article, I will show you how to upload images to folder and display uploaded images in ASP.Net GridView using C#. I am using visual studio 2012 framework and Microsoft sql server 2008 R2 for this demo.
Right click on your project -> Add -> new item -> Add Index.aspx file.
Now copy & paste following code inbetween form element of your Index.aspx.
1 2 3 4 5 6 7 8 9 10 11 | <div> <br /><br /> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false"> <Columns> <asp:BoundField DataField="Text" /> <asp:ImageField DataImageUrlField="Value" ControlStyle-Height="100" ControlStyle-Width="100" /> </Columns> </asp:GridView> </div> |
Double click on upload button and add following code
1 2 3 4 5 6 | if (FileUpload1.HasFile) { string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName); Response.Redirect(Request.Url.AbsoluteUri); } |
Copy and paste following code on page load event
1 2 3 4 5 6 7 8 9 10 11 12 | if (!IsPostBack) { string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/")); List<ListItem> files = new List<ListItem>(); foreach (string filePath in filePaths) { string fileName = Path.GetFileName(filePath); files.Add(new ListItem(fileName, "~/Images/" + fileName)); } GridView1.DataSource = files; GridView1.DataBind(); } |
01 July 2019 2774 Written By: Rohit
© 2020 Tech Study. All rights reserved | Developed by Tech Study| Privacy Policy | Sitemap