简体   繁体   中英

How to upload image file in gridview?

I have a gridview that shows an image as part of a column. In Edit mode, I would like to let the user upload a new image file, so I'm using the FileUpload control in the edit part of the template.

When I click on update it's showing me this:

在此处输入图片说明

My code:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label lb = GridView1.HeaderRow.FindControl("Label1") as Label;
    GridViewRow row = GridView1.Rows[e.RowIndex];
    FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
    if (fu.HasFile)
    {
        string file = System.IO.Path.Combine(Server.MapPath("~/uploadedimages/"), fu.FileName);
        fu.SaveAs(file);

        using (Ex_RepeaterEntities entities = new Ex_RepeaterEntities())
        {
            Student students = (from e1 in entities.Students
                                where e1.Id == Convert.ToInt32(lb.Text)
                                select e1).First();
            students.Images = file;
            entities.SaveChanges();
        }
    }
}

After a lot of searching I found solution of above error by using this code:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
        int RowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
        FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("fileupload") as FileUpload;
        if (fileUpload.HasFile)
        {
           fileUpload.SaveAs(Server.MapPath("~/uploadedimages/" + fileUpload.FileName));
        }
}

and at page.aspx:

<asp:TemplateField HeaderText="Upload Image" SortExpression="Names">
     <EditItemTemplate>
          <asp:FileUpload runat="server" ID="fileupload" />
     </EditItemTemplate>
     <ItemTemplate>
          <asp:Image ImageUrl="~/uploadedimages/1.jpg" runat="server" ID="image" />
     </ItemTemplate>
 </asp:TemplateField>

But a little problem here is to solve which is that file is not saving.

Finally got my own solution of above post. Here is code to be changed:

if (fileUpload.HasFile)
{
       fileUpload.SaveAs(Server.MapPath("uploadedimages/" + fileUpload.FileName));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM