Reputation: 9
protected void btn_Insert_Click(object sender, EventArgs e)
{
int result = 0;
storageprice sp = new storageprice(tb_PriceID.Text, tb_StorageName.Text, tb_Desc.Text, decimal.Parse(tb_StorePrice.Text), int.Parse(tb_OutletID.Text));
result = sp.StoragePricingInsert();
if (result > 1)
{
Response.Write("<script>alert('Storage Remove Successfullly');</script>");
}
else
{
Response.Write("<script>alert('Storage Removal not successfull');</script>");
}
Response.Redirect("StoragePricingView.aspx");
}
C# file
public int StoragePricingInsert()
{
int result = 0;
string queryStr = "INSERT INTO StoragePricing(Pricing_Id, Name, Description, Pricing, Outlet_Id)"
+ "values (@Pricing_ID, @Name, @Description, @Pricing, @Outlet_Id)";
try
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("@Pricing_Id", this.Pricing_Id);
cmd.Parameters.AddWithValue("@Name", this.Name);
cmd.Parameters.AddWithValue("@Description", this.Description);
cmd.Parameters.AddWithValue("@Pricing", this.Pricing);
cmd.Parameters.AddWithValue("@Outlet_Id", this.OutletId);
conn.Open();
result += cmd.ExecuteNonQuery(); // returns no. of rows affected. Must be >0
conn.Close();
return result;
}
catch (Exception ex)
{
return 0;
}
}
How do I only insert 1 unique string into my primary key?
Let's say I put "bt01"
if I add and press "bt01"
it would prompt already in use.
Thanks a lot!
Upvotes: 0
Views: 43
Reputation: 4808
Depends. If you don't care what the ID value is, let the database handle it - it should automatically assign the value depending on how it's configured - use an identity column as the primary key and the value will be assigned for you.
If you want to assign the value programmatically, you'll need to have a method which finds the highest value integer in your database, increment it and assign the value to your new record. You need to place both that method and the save method into a singleton to make it thread safe so the same value can't be added twice.
You could also look at using a Guid as your primary key instead of an int.
Upvotes: 1