I have a program which enters inputted details into a SQL Server database, the program is working well and data will go into SQL Server. I am sending customerID
, customerName
, CustomerAddress
, CustomerAddedDate
to the SQL Server database.
How do I go about creating an if...else
statement to display a message box to the user to inform them if data was inserted successfully or not, and if not, why not.
Also, how can I automatically have the next available customerID
(which is the integer primary key in the SQL Server database) show up automatically in the customerID
textbox?
I imagine a code which reads from the customerID
column in SQL Server database and then add +1 to it and setting that to the properties of customerID
aka textbox1
but perhaps there is a better idea?
My program:
My code:
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=LAPTOP\\SQLEXPRESS02;Initial Catalog=Greenwich_Butcher;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string dat = "Insert into [CustomerDetails](CustomerID, CustomerName, CustomerAddress, CustomerAddedDate) Values('" + Convert.ToInt32(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + Convert.ToString(dateTimePicker1.Text) + "')";
SqlCommand com = new SqlCommand(dat, con);
con.Open();
int rowsAffected = com.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Record inserted succesfully");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
dateTimePicker1.Text = "";
}
else
{
MessageBox.Show("Record not inserted succesfully");
}
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}