FileUpload Null引用错误

时间:2013-10-12 13:08:12

标签: c# asp.net file-upload

我想使用FileUpload Control将Image保存到数据库。点击BtnSave后,HasFiles总是返回false。我尝试使用和不使用UpdatePanel但无法找到解决方案。

我的代码是:

  protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == true)
        {
            var ChNumber = txtNumber.Text;

            string img = this.FileUpload1.PostedFile.FileName;
  //Save image to database function
        }
 else
 {
  lblStatus.Text="Image not Uploaded";
 }
 }

1 个答案:

答案 0 :(得分:0)

尝试使用没有UpdatePanel的简单表单。这是标记:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="BtnSave" runat="server" Text="Button" OnClick="BtnSave_Click" />
        <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
        <asp:Label ID="lblStatus" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

以下是代码:

using System;

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == true)
        {
            var ChNumber = txtNumber.Text;

            string img = this.FileUpload1.PostedFile.FileName;
            //Save image to database function
        }
        else
        {
            lblStatus.Text = "Image not Uploaded";
        }
    }
}

我在if (FileUpload1.HasFile == true)设置了一个brekapoint,并看到上传的文件在那里。