Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file upload in gridview

I need to add a column with a file upload control to my grid view so that I can upload files against any particular row. Is it possible to do this, ideally I need to be able to do this without putting the gridview into it's edit state.

like image 341
user517406 Avatar asked May 12 '11 08:05

user517406


1 Answers

You can use this within the as follows:

   <asp:TemplateField HeaderText="UploadImage">

   <ItemTemplate>

      <asp:Image ImageUrl="~/images/1.jpg" runat="server" ID="image" /> // shown only when not in edit mode

    </ItemTemplate>

   <EditItemTemplate>

       <asp:FileUpload ID="FileUpload1" runat="server" /> // shown only in edit mode

   </EditItemTemplate>

  </asp:TemplateField>

At last include a as follows to enter edit mode.

       <asp:commandField showEditButton="true" showCancelButton="true"> 

Then add two events as follows:

   protected void GridView1_RowEditing(object sender, GridViewUpdateEventArgs e)
   { 
       gvwID.EditIndex=e.NewEditIndex;
       BindGrid();
   }   

    protected void GridView1_RowCancelEdit(object sender, GridViewUpdateEventArgs e)
    {  
          gvwID.EditIndex=-1;
           BindGrid();             
    }   

The FileUpload control, will not automatically save the uploaded file. To save the file you need to use the FileUpload control’s SaveAs method. Before you can use the SaveAs method you need to get the instance of the FileUpload control for the row you are editing. To get the instance of the control you can hook up to the GridView’s RowUpdating event. The following code will get the instance of the FileUpload control and save the uploaded file:

   protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
   {

       int RowID=Convert.ToInt32(gvwID.DataKeys[e.RowIndex].value);

       FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as   FileUpload; 

     if(fileUpload.HasFile)
     {

       fileUpload.SaveAs(System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName)); 

        //update db using the name of the file corresponding to RowID
      }

       gvwID.EditIndex=-1;
       BindGrid();

    }

Hope this will help...

like image 107
Harun Avatar answered Nov 04 '22 05:11

Harun