-1

i'm creat db in sql like this

ImageId Int(set identity property=true)

ImageName Varchar(50)

Image image

and my aspx like this

<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>

my code like this

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();
}

but when run this application this error exsiption appear

Cannot insert the value NULL into column 'ImageId', table 'DressDB .dbo.Image'; column does not allow nulls. INSERT fails.
The statement has been terminated.

how i can solve that please?

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Hala Qaseam
  • 11
  • 1
  • 5
  • 2
    The table in your database doesn't match your narrative at the top. Specifically, in the database, `ImageId` isn't `IDENTITY`. – Damien_The_Unbeliever Oct 03 '12 at 07:07
  • With @Damien_The_Unbeliever. Please show the actual SQL used to create the table, show only the relevant code and above all: show what you have tried to solve this error, since it's pretty self-explanatory. – CodeCaster Oct 03 '12 at 07:14

2 Answers2

3

Mahmoud Gamal is correct, however if you feel more comfortable doing it with the design-view in Management Studio, this is the option you are looking for:

How to set a column as identity in the designer

That will set the value for the first inserted row to 1, and then increase that counter by 1 for each new row inserted to the table.

TheQ
  • 6,858
  • 4
  • 35
  • 55
2

The error is pretty clear. You can't insert NULL Values in this column because it doesn't allow NULL values.

how i can solve that please?

Make this column ImageId auto incremental like so:

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

Then your INSERT statement:

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

Should work properly.

But in your case where the table already contains data, you can't do that directly as pointed out by @Damien_The_Unbeliever. In this case1:

You have 2 options,

  • Create a new table with identity & drop the existing table

  • Create a new column with identity & drop the existing column

See the following question for more details:


1 Quoted From this answer

Community
  • 1
  • 1
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
  • You can't directly alter a table to change an existing column's `IDENTITY` property. See [this question](http://stackoverflow.com/questions/1049210/adding-an-identity-to-an-existing-column) for some ways to do it. – Damien_The_Unbeliever Oct 03 '12 at 07:29
  • @Damien_The_Unbeliever - Sorry, I added this in my answer. See my edit. – Mahmoud Gamal Oct 03 '12 at 07:42