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();
}
}
}
Munesh SharmaPosted May 21, 2014, 12:52 AM
VulpesPosted May 20, 2014, 11:21 AM
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";
IsraelPosted May 20, 2014, 11:12 AM
VulpesPosted May 20, 2014, 9:57 AM
// blah
int count = (int)comm.ExecuteScalar();
if (count == 0)
{
// blah
}
IsraelPosted May 20, 2014, 9:52 AM
VulpesPosted May 20, 2014, 9:28 AM
{
}
else
{
conn.Close(); // don't forget to close connection if no insertion was needed
}
Mfwamba TshimangaPosted May 20, 2014, 9:02 AM
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();
}
}
}Naveed ZamanPosted May 13, 2014, 7:16 AM
VulpesPosted May 10, 2014, 1:26 PM
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
}