-1

我像这样在 sql 中创建 db

ImageId Int(set identity property=true)

ImageName Varchar(50)

Image image

和我这样的aspx

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>Inserting images into databse and displaying images with gridview</title>
    <style type="text/css">
      .Gridview
      {
        font-family:Verdana;
        font-size:10pt;
        font-weight:normal;
        color:black;
        width:500px;
      }
    </style>
  </head>
  <body>
    <form id="form1" runat="server">
      <div>
        <table>
          <tr>
            <td>
              Image Name:
            </td>
            <td>
              <asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
            </td>
          </tr>
          <tr>
            <td>
              Upload Image:
            </td>
            <td>
              <asp:FileUpload ID="fileuploadImage" runat="server" />
            </td>
          </tr>
          <tr>
            <td>
            </td>
            <td>
              <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
            </td>
          </tr>
        </table>
      </div>
      <div>
        <asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
          <Columns>
            <asp:BoundField HeaderText = "Image Name" DataField="imagename" />
            <asp:TemplateField HeaderText="Image">
              <ItemTemplate>
                <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
              </ItemTemplate>
            </asp:TemplateField>
          </Columns>
        </asp:GridView>
      </div>
    </form>
  </body>
</html>

我的代码是这样的

string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    BindGridData();
  }
}
/// <summary>
/// btnUpload_Click event is used to upload images into database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
  //Condition to check if the file uploaded or not
  if (fileuploadImage.HasFile)
  {
    //getting length of uploaded file
    int length = fileuploadImage.PostedFile.ContentLength;
    //create a byte array to store the binary image data
    byte[] imgbyte = new byte[length];
    //store the currently selected file in memeory
    HttpPostedFile img = fileuploadImage.PostedFile;
    //set the binary data
    img.InputStream.Read(imgbyte, 0, length);
    string imagename = txtImageName.Text;
    //use the web.config to store the connection string
    SqlConnection connection = new SqlConnection(strcon);
    connection.Open();
    SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)", connection);
    cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename;
    cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
    int count = cmd.ExecuteNonQuery();
    connection.Close();
    if (count == 1)
    {
      BindGridData();
      txtImageName.Text = string.Empty;
      ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
    }
  }
}
/// <summary>
/// function is used to bind gridview
/// </summary>
private void BindGridData()
{
  SqlConnection connection = new SqlConnection(strcon);
  SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
  SqlDataAdapter daimages = new SqlDataAdapter(command);
  DataTable dt = new DataTable();
  daimages.Fill(dt);
  gvImages.DataSource = dt;
  gvImages.DataBind();
  gvImages.Attributes.Add("bordercolor", "black");
}
string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
  string imageid = context.Request.QueryString["ImID"];
  SqlConnection connection = new SqlConnection(strcon);
  connection.Open();
  SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);
  SqlDataReader dr = command.ExecuteReader();
  dr.Read();
  context.Response.BinaryWrite((Byte[])dr[0]);
  connection.Close();
  context.Response.End();
}

但是当运行这个应用程序时,会出现这个错误

无法将值 NULL 插入到列“ImageId”、表“DressDB .dbo.Image”中;列不允许空值。插入失败。
该语句已终止。

请问我该如何解决?

4

2 回答 2

3

Mahmoud Gamal 是正确的,但是如果您觉得使用 Management Studio 中的设计视图更舒服,那么您正在寻找的选项是:

如何在设计器中将列设置为标识

这会将第一个插入行的值设置为 1,然后对于插入到表中的每个新行将该计数器增加 1。

于 2012-10-03T07:29:33.803 回答
2

错误很明显。您不能在此列中插入 NULL 值,因为它不允许NULL值。

请问我该如何解决?

使该列ImageId自动递增,如下所示:

ALTER TABLE Images
ALTER IMAGE_ID INT NOT NULL IDENTITY(1, 1);

然后你的INSERT陈述:

INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)

应该可以正常工作。

但是在您的表已经包含数据的情况下,您不能像@Damien_The_Unbeliever 指出的那样直接执行此操作。在这种情况下1

你有2个选择,

  • 创建具有标识的新表并删除现有表

  • 创建具有标识的新列并删除现有列

有关详细信息,请参阅以下问题:


1引用自此答案

于 2012-10-03T07:08:33.320 回答