private void btnSave_Click_1(object sender, EventArgs e)
{
{
conn = new SqlConnection(connstr);
comm = new SqlCommand();
conn.Open();
SqlParameter code = new SqlParameter("@code", SqlDbType.NChar);
comm.Parameters.Add(code);
code.Value = mycode.Text;
comm.Connection = conn;
comm.CommandText = "insert into classenumer values(@code)";
try
{
comm.ExecuteNonQuery();
MessageBox.Show("Good saving!");
mycode.Clear();
}
catch (Exception)
{
MessageBox.Show("Sorry, not saved");
}
finally
{
conn.Close();
}
}
}
VulpesRank #55 · 29.2K reputationPosted May 10, 2014, 9:26 AM EDT
Failing that you'd have to run a Select query, prior to the Insert statement, to see whether a record whose code column with a value of mycode.Text already exists.
comm.CommandText = "select count(*) from classenumer where code = @code";
int count = (int)comm.ExecuteScalar();
if (count == 0)
{
// make your insertion
}
Naveed ZamanRank #565 · 4.3K reputationPosted May 13, 2014, 3:16 AM EDT
Mfwamba Tshimanga155 reputationPosted May 20, 2014, 5:02 AM EDT
Vulves, I do try your code in mine as you can see. Its works. Means when the number for example is the same its doenst save. But when the code is different its says "good saving" as I do write in my code.
Then when I open my sql database to see if it's saved. Nothing have been saved. It's strange!
Please have a look:
private void btnSave_Click_1(object sender, EventArgs e)
{
{
conn = new SqlConnection(connstr);
comm = new SqlCommand();
conn.Open();
SqlParameter code = new SqlParameter("@code", SqlDbType.NChar);
comm.Parameters.Add(code);
code.Value = mycode.Text;
comm.Connection = conn;
//Here
comm.CommandText = "select count(*) from classenumer where code = @code";
int count = (int)comm.ExecuteScalar();
if (count == 0)
try
{
comm.ExecuteNonQuery();
MessageBox.Show("Good saving!");
mycode.Clear();
}
catch (Exception)
{
MessageBox.Show("Sorry, not saved");
}
finally
{
conn.Close();
}
}
}VulpesRank #55 · 29.2K reputationPosted May 20, 2014, 5:28 AM EDT
{
}
else
{
conn.Close(); // don't forget to close connection if no insertion was needed
}
IsraelRank #1,223 · 1.5K reputationPosted May 20, 2014, 5:52 AM EDT
VulpesRank #55 · 29.2K reputationPosted May 20, 2014, 5:57 AM EDT
// blah
int count = (int)comm.ExecuteScalar();
if (count == 0)
{
// blah
}
IsraelRank #1,223 · 1.5K reputationPosted May 20, 2014, 7:12 AM EDT
VulpesRank #55 · 29.2K reputationPosted May 20, 2014, 7:21 AM EDT
if (count == 0)
onwards.
The earlier code should be as you already had it:
conn = new SqlConnection(connstr);
comm = new SqlCommand();
conn.Open();
SqlParameter code = new SqlParameter("@code", SqlDbType.NChar);
comm.Parameters.Add(code);
code.Value = mycode.Text;
comm.Connection = conn;
comm.CommandText = "select count(*) from classenumer where code = @code";
Munesh SharmaRank #174 · 13.9K reputationPosted May 20, 2014, 8:52 PM EDT