在GridView控件文件上传
我需要用一个文件上传控件到我的网格视图中添加一列,这样我可以上传文件针对任何特定行。是否有可能做到这一点,最好我需要能够做到这一点,而无需把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.
您可以按如下方式中的使用:
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();
}
FileUpload控件不会自动保存上传的文件。要保存文件,你需要使用FileUpload控件的SaveAs方法。在可以使用SaveAs方法,你需要得到FileUpload控件为你正在编辑的行的实例。为了得到控制的情况下,你可以连接到GridView的RowUpdating事件。下面code将得到FileUpload控件的实例,并保存上传的文件:
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...