c# - Posting a message box when database records are added, or when an exception is generated
问题描述
sorry if this is a stupid question, but can you help me add some code to my application that generates a MessageBox whenever someone makes a successful addition to the table, and another MessageBox whenever an exception is generated that prevents the desired information from being added to the table? My code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
public partial class AddJob : Form
{
public AddJob()
{
InitializeComponent();
}
private void AddJob_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\richard.schade\Desktop\IKJobs\WindowsFormsApp1\ikData.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO openJobs (jobTitle, jobDescription, dateOpened, jobsiteLink, jobLocation) VALUES (@jobTitle, @jobDescription, @dateOpened, @jobsiteLink, @jobLocation)", con);
cmd.Parameters.AddWithValue("@jobTitle", textBox1.Text);
cmd.Parameters.AddWithValue("@jobDescription", textBox5.Text);
cmd.Parameters.AddWithValue("@dateOpened", textBox4.Text);
cmd.Parameters.AddWithValue("@jobsiteLink", textBox3.Text);
cmd.Parameters.AddWithValue("@jobLocation", textBox2.Text);
cmd.ExecuteNonQuery();
}
}
}
Thanks for your help, I have already learned a lot from this forum.
解决方案
Wrap the contents of your method in try
/catch
Do MessageBox.Show(exception msg)
within catch
And do MessageBox.Show(successfully done)
as last line of try.
Eg
Try{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\richard.schade\Desktop\IKJobs\WindowsFormsApp1\ikData.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO openJobs (jobTitle, jobDescription, dateOpened, jobsiteLink, jobLocation) VALUES (@jobTitle, @jobDescription, @dateOpened, @jobsiteLink, @jobLocation)", con);
cmd.Parameters.AddWithValue("@jobTitle", textBox1.Text);
cmd.Parameters.AddWithValue("@jobDescription", textBox5.Text);
cmd.Parameters.AddWithValue("@dateOpened", textBox4.Text);
cmd.Parameters.AddWithValue("@jobsiteLink", textBox3.Text);
cmd.Parameters.AddWithValue("@jobLocation", textBox2.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("done") ;
}
Catch(Exception ezx) {
MessageBox.Show("bad");
}