-
Apr 8th, 2025, 11:17 AM
#1
Thread Starter
Lively Member
C# : My code Doesn't work to prevent repeating barcode value
C# : My code Doesn't work to prevent repeating barcode value
How to fix it ?
Code:
string msg = "";
try
{
//Add Data
DB.run("insert into item values('" + textBox1.Text.Replace("'", "") + "','" + textBox2.Text.Replace("'", "") + "','" + textBox3.Text.Replace("'", "") + "','" + textBox4.Text.Replace("'", "") + "','" + textBox5.Text.Replace("'", "") + "'," + textBox6.Text.Replace("'", "") + ")");
msg += "Item Has Been Added Successfully";
//Add Image
if (textBox7 != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
DB.cmd.Parameters.Clear();
DB.cmd.Parameters.AddWithValue("@img", ms.ToArray());
DB.run("insert into item_image values(" + textBox1.Text.Replace("'", "") + ",@img)");
msg += "\n Item's Image Has Been Added Successfully";
MessageBox.Show(msg);
if (Application.OpenForms["frmItemSearch"] != null)
{
((frmItemSearch)Application.OpenForms["frmItemSearch"]).fillData();
}
}
}
catch (SqlException ex)
{
if (ex.Number == 2627)
MessageBox.Show("Barcode Can Not Be Duplicated.");
else
MessageBox.Show(ex.Message);
}
}
}
Code:
CREATE TABLE [dbo].[item] (
[item_number] INT NOT NULL,
[item_name] VARCHAR (250) NULL,
[minimum_quantity] NUMERIC (9, 2) NULL,
[buy_price] NUMERIC (9, 2) NULL,
[sale_price] NUMERIC (9, 2) NULL,
[barcode] VARCHAR (60) NOT NULL,
CONSTRAINT [PK_item] PRIMARY KEY CLUSTERED ([barcode] ASC, [item_number] ASC),
UNIQUE NONCLUSTERED ([item_number] ASC)
);
Last edited by Max45; Apr 8th, 2025 at 12:08 PM.
-
Apr 9th, 2025, 12:34 AM
#2
Re: C# : My code Doesn't work to prevent repeating barcode value
First of all, stop using string concatenation to insert values into SQL code. You obviously know how to use parameters because you're doing it to save an image, so do it everywhere.
-
Apr 9th, 2025, 12:35 AM
#3
Re: C# : My code Doesn't work to prevent repeating barcode value
As for your issue, there is no unique constraint on the barcode. You have only required the combination of barcode and item_number to be unique, not barcode on its own.
-
Apr 9th, 2025, 09:01 AM
#4
Thread Starter
Lively Member
Re: C# : My code Doesn't work to prevent repeating barcode value
 Originally Posted by jmcilhinney
As for your issue, there is no unique constraint on the barcode. You have only required the combination of barcode and item_number to be unique, not barcode on its own.
CREATE TABLE [dbo].[item] (
[item_number] INT NOT NULL PRIMARY KEY,
[item_name] VARCHAR (250) NULL,
[minimum_quantity] NUMERIC (9, 2) NULL,
[buy_price] NUMERIC (9, 2) NULL,
[sale_price] NUMERIC (9, 2) NULL,
[barcode] VARCHAR (60) NOT NULL UNIQUE
);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|