ثبت تصویر و به روزرسانی درGridView بدون اتصال به پایگاه داده
پنجشنبه 9 مهر 1394در این مقاله قصد داریم که نحوه ثبت تصویر و به روز رسانی آن را به وسیله ی GridView بدون اتصال به هر نوع دیتا بیس آموزش دهیم.
قبل از هر چیز می توانید دو مقاله ی زیر را مطالعه بفرمایید:
1-اتصال داده با استفاده از ListView، GridView بدون استفاده از DataBase در Asp.Net
2-اتصال داده در ListView با کلیک کردن LinkButton
قدم اول:ابتدا Visual Studio را باز کنید و یک پروژه ی جدید بسازید.
قدم دوم:راست کلیک کرده و یک پروژه ی WebForm جدید بسازید.
قدم سوم:کلاس Css زیر را در قسمت Head صفحه بنویسید:
<style type="text/css"> body { color: #333; text-align: center; background-color: aqua; } </style>
داخل DesignUI قطعه کد زیر را بنویسید:
برای انتخاب تصویر باید از FileUploadاستفاده نمایید.
<div style="float: left"> <asp:Label ID="Label1" runat="server" Text="Display an Image :"></asp:Label> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Display" OnClick="UploadImage" /> </div> <asp:Label ID="lblResult" runat="server" /> <br /> <br /> <div style="float: left"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="imgname" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" HeaderStyle-BackColor="Tomato"> <Columns> <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px"> <ItemTemplate> <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <asp:Label ID="lblDate" runat="server" ClientIDMode="Static" Text='<%# DataBinder.Eval(Container.DataItem,"imgdate") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="lblTextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"imgname") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Image Name"> <ItemTemplate> <asp:Image ID="Image" runat="server" Height="100px" Width="20%" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"imgurl") %>' /> </ItemTemplate> <EditItemTemplate> <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("imgurl") %>' Height="80px" Width="100px" /><br /> <asp:FileUpload ID="FileUpload1" runat="server" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderStyle-Width="150px"> <ItemTemplate> <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton> <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton> <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div
کل کد ما در صفحه ی DesignUI به صورت زیر خواهد بود :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> body { color: #333; text-align: center; background-color: aqua; } </style> </head> <body> <form id="form1" runat="server"> <div style="float: left"> <asp:Label ID="Label1" runat="server" Text="Display an Image :"></asp:Label> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Display" OnClick="UploadImage" /> </div> <asp:Label ID="lblResult" runat="server" /> <br /> <br /> <div style="float: left"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="imgname" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" HeaderStyle-BackColor="Tomato"> <Columns> <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px"> <ItemTemplate> <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <asp:Label ID="lblDate" runat="server" ClientIDMode="Static" Text='<%# DataBinder.Eval(Container.DataItem,"imgdate") %>'></asp:Label> </ItemTemplate> <%-- <EditItemTemplate> <asp:TextBox ID="txt_Date" runat="server" ClientIDMode="Static" Text='<%#DataBinder.Eval(Container.DataItem,"imgdate") %>'></asp:TextBox> </EditItemTemplate>--%> </asp:TemplateField> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="lblTextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"imgname") %>'></asp:Label> </ItemTemplate> <%--<EditItemTemplate> <asp:TextBox ID="txt_TextBox1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"imgname") %>'></asp:TextBox> </EditItemTemplate>--%> </asp:TemplateField> <asp:TemplateField HeaderText="Image Name"> <ItemTemplate> <asp:Image ID="Image" runat="server" Height="100px" Width="20%" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"imgurl") %>' /> </ItemTemplate> <EditItemTemplate> <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("imgurl") %>' Height="80px" Width="100px" /><br /> <asp:FileUpload ID="FileUpload1" runat="server" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderStyle-Width="150px"> <ItemTemplate> <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton> <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton> <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form> </body> </html>
قدم چهارم:NameSpace های زیر را وارد نمایید.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;
داخل Code Behind قطعه کد زیر را بنویسید:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class BindImageWithoutDB : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindImage(); } } public class clsImg { //property for image uploading public string imgurl { get; set; } public string imgname { get; set; } public DateTime imgdate { get; set; } } protected void BindImage() { string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/TestImage/")); List<clsImg> images = new List<clsImg>(filesindirectory.Count()); //file time DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath("~/Images/TestImage/")); var files = from file in DirInfo.EnumerateFiles() orderby file.LastWriteTime descending select file; DateTime lastModifie = System.DateTime.Now; DateTime creationTime; DateTime lastAccessTime; foreach (var fi in files) { lastModifie = fi.LastWriteTimeUtc; creationTime = fi.CreationTimeUtc; lastAccessTime = fi.LastWriteTimeUtc; images.Add(new clsImg { imgdate = lastModifie, imgname = fi.Name.ToString(), imgurl = String.Format("~/Images/TestImage/{0}", System.IO.Path.GetFileName(fi.Name.ToString())) }); } GridView1.DataSource = images; GridView1.DataBind(); } protected void UploadImage(object sender, EventArgs e) { if (FileUpload1.HasFile) { string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/TestImage/") + fileName); Response.Redirect(Request.Url.AbsoluteUri); } } //editing event protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindImage(); } //row updation event //here we try to update modification time but this I can't achieve this currently protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //find image id of edit row string imageId = GridView1.DataKeys[e.RowIndex].Value.ToString(); // find values for update Label name = (Label)GridView1.Rows[e.RowIndex].FindControl("lblTextBox1"); FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1"); string path = "~/Images/TestImage/"; string path1; if (FileUpload1.HasFile) { ImageDeleteFromFolder(name.Text.ToString()); //path += FileUpload1.FileName; path += FileUpload1.FileName; //save image in folder FileUpload1.SaveAs(MapPath(path)); } else { // use previous user image if new image is not changed Image img = (Image)GridView1.Rows[e.RowIndex].FindControl("img_user"); path = img.ImageUrl; } GridView1.EditIndex = -1; BindImage(); } //cancelation event protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindImage(); } //deleting event protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex]; // Label lbldeleteid = (Label)row.FindControl("lblTextBox1"); Label lblDeleteImageName = (Label)row.FindControl("lblTextBox1"); //con = new SqlConnection(connStr); ImageDeleteFromFolder(lblDeleteImageName.Text.ToString()); BindImage(); } /// <summary> /// This function is used to delete image from folder when deleting in gridview. /// </summary> /// <param name="imagename">image name</param> protected void ImageDeleteFromFolder(string imagename) { string file_name = imagename; string path = Server.MapPath(@"~/Images/TestImage/" + imagename); FileInfo file = new FileInfo(path); if (file.Exists)//check file exsit or not { file.Delete(); lblResult.Text = file_name + " file deleted successfully"; lblResult.ForeColor = System.Drawing.Color.Green; } else { lblResult.Text = file_name + " This file does not exists "; lblResult.ForeColor = System.Drawing.Color.Red; } } }
خروجی به صورت زیر خواهد بود:
- ASP.net
- 1k بازدید
- 2 تشکر