FileUpload错误?

时间:2017-11-20 02:58:56

标签: c# asp.net

对象引用未设置为对象的实例       我的.ascx

    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id_progress_legal_dokumen" DataSourceID="SqlDataSource4" PageSize="25" ShowHeaderWhenEmpty="True" CssClass="table table-striped table-condensed gvCustom" BackColor="White" AllowPaging="True" OnRowCommand="GridView2_RowCommand">
                <Columns>
        <asp:TemplateField HeaderText="Upload File">
                        <ItemTemplate>
                            <asp:FileUpload ID="fileupload1" runat="server" />
                            <asp:Button ID="bntUpload" runat="server" Text="Upload" OnClick="bntUpload_Click" />

                        </ItemTemplate>
                    </asp:TemplateField>
           </Columns>
     </asp:GridView>

event buttonclick我的代码ascx.cs

 protected void bntUpload_Click(object sender, EventArgs e)
    {

string folderpath = Server.MapPath("~/Upload/");
        FileUpload fileupload = (FileUpload)GridView2.FindControl("fileupload1");
        try
        {
            if(!Directory.Exists(folderpath))
            {
                Directory.CreateDirectory(folderpath);
            }
//this my error
                fileupload.SaveAs(folderpath + Path.GetFileName(fileupload.FileName));


  }
        catch (Exception ex)
        {

            myfeedback._error(ex);
        }


    }

我的错误在哪里? //错误fileupload.SaveAs(folderpath + Path.GetFileName(fileupload.FileName));

1 个答案:

答案 0 :(得分:1)

当你在行中时,你无法直接在GridView中找到一个控件,你必须在gridview的行中找到它。

使用: GridView1_RowDataBound事件

if(e.Row.RowType == DataControlRowType.DataRow)
    {
        FileUpload fileupload = 
(FileUpload)e.Row.FindControl("fileupload1");
    }

OR

 DataRow r = (DataRow)sender;
 FileUpload fileupload = (FileUpload)r.FindControl("fileupload1");