c#
  • asp.net
  • gridview
  • response.transmitfile
  • 2017-09-27 42 views 0 likes 
    0

    我有一個GridView名爲gvEmplAttachments有3列:文件不是從GridView控件的單擊事件下載

    • ID
    • 文件名
    • 文件路徑

    每一行都有一個LinkButton這將允許用戶下載該文件,該按鈕編碼如下:

    <asp:LinkButton id="lbViewFile" runat="server" CommandName="ViewFile" CommandArgument='<%# Container.DataItemIndex %>' >View</asp:LinkButton> 
    

    GridView控件設置下列要求:

    OnRowCommand ="gvEmplAttachments_OpenAttachment_RowCommand" 
    

    因此,它會在代碼隱藏


    執行的功能在我隱藏我有這樣的功能:

    protected void gvEmplAttachments_OpenAttachment_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
        if (e.CommandName == "ViewFile") 
        { 
         //Get rowindex 
         int rowindex = Convert.ToInt32(e.CommandArgument); 
         //Get the Row 
         GridViewRow gvr = gvUaSettings.Rows[rowindex]; 
         //Get the Needed Values 
         Label lblPath = gvr.FindControl("lblFilePath") as Label; 
         Label lblName = gvr.FindControl("lblFileName") as Label; 
         //String The values 
         string fileName = lblName.Text; 
         string filePath = Server.MapPath(lblPath.Text); 
         //Should Download the file 
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
         response.ClearContent(); 
         response.Clear(); 
         response.ContentType = "application/x-unknown"; 
         response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); 
         response.TransmitFile(filePath); 
         response.Flush(); 
         response.End(); 
        } 
    } 
    

    但問題是當我點擊按鈕,我得到這個錯誤:

    Object reference not set to an instance of an object

    我的問題是,我錯過了什麼會導致空值。 由於網格顯示正確的FileName和FilePath。

    enter image description here

    +1

    至於你提到你**的GridView ID **是'gvEmplAttachments',但你寫的代碼搶觸發** OnCommand **事件的Gridview行有不同的GridView ID'GridViewRow gvr = gvUaSettings.Rows [rowindex];'這是正確的還是代碼錯位?可能它沒有得到正確的Gridview Row。 –

    +0

    [什麼是NullReferenceException,以及如何解決它?]可能的重複(https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it ) – VDWWD

    +0

    @Rojalin Sahoo好抓!糾正了這個問題。 - 如果您將此作爲答案提交,我會爲您標記。 – Tommy

    回答

    0

    至於你提到你的GridView ID是gvEmplAttachments,但你的代碼寫入到搶其觸發因素是具有不同的GridView ID GridViewRow gvr = gvUaSettings.Rows[rowindex];按需事件的GridView的行。

    你可以嘗試下面的代碼讀取該行觸發命令事件:

    GridViewRow gvr = gvEmplAttachments.Rows[rowindex];

    相關問題