如何在网格视图中的项目模板中添加文件上传控件。不能从gridview.how的上传控件获取文件名,以便在gridview中为每一行添加文件上传控件
<asp:GridView runat="server" ID="gridviewAddPo" AutoGenerateEditButton="false" OnRowEditing="gridviewAddPo_RowEditing" OnRowUpdating="gridviewAddPo_RowUpdating" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Upload" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<Columns/>
</asp:Gridview>
背后的代码是:
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);//getting errrorhow ot
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (System.IO.BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["kernelCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
.....
}
答案 0 :(得分:1)
将错误行替换为低于4行
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
FileUpload fu = gvr.cells[1].FindControl("FileUpload1") as FileUpload;
string filename = Path.GetFileName(fu.PostedFile.FileName);