-4

Object reference not set to an instance of an object my .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 My code behind 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);
        }


    }

where is my mistake ? //error fileupload.SaveAs(folderpath + Path.GetFileName(fileupload.FileName));

Rahmat
  • 107
  • 8

1 Answers1

1

You cannot find a control in the GridView directly when its in the row, you have to find it in the row of the gridview.

Use either: GridView1_RowDataBound event

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

OR

 DataRow r = (DataRow)sender;
 FileUpload fileupload = (FileUpload)r.FindControl("fileupload1");
Sunil
  • 3,279
  • 10
  • 19
  • 27