【问题标题】:How to upload image file in gridview?如何在gridview中上传图像文件?
【发布时间】:2015-12-09 11:36:58
【问题描述】:

我有一个网格视图,它将图像显示为列的一部分。在编辑模式下,我想让用户上传一个新的图像文件,所以我在模板的编辑部分使用了 FileUpload 控件。

当我点击更新时,它向我显示:

我的代码:

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();
        }
    }
}

【问题讨论】:

  • 似乎是你没有为 fu 设置值,这意味着它在 fileupload 中找不到任何名为 fileupload 的控件b>row.Cells[0]!!你能说明你在哪里/如何获取/设置 row 变量吗?
  • 我只是使用行变量来查找我的控件就是这样。我在谷歌上发现了这个技巧。在我使用之前:'FileUpload tb = GridView1.FindControl("fileupload") as FileUpload ;'但它也给了我同样的错误
  • @cramopy 我发布了我自己的问题答案,请看一下。

标签: c# asp.net gridview file-upload


【解决方案1】:

经过大量搜索,我使用以下代码找到了上述错误的解决方案:

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));
        }
}

在 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>

但是这里有个小问题是解决那个文件没有保存。

【讨论】:

    【解决方案2】:

    终于得到了我自己对上述帖子的解决方案。这是要更改的代码:

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

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2017-02-18
      • 2017-04-08
      相关资源
      最近更新 更多