I am completely new to the C# development world and I am working on a small application which will allow a user to add basic employee details to a employee table. I can get the code to add a row to the table but the question I asked myself is "What would happen if the user were to add a record which already exists?" Answer, it would simply add another row and so I could end up with duplicated records, how could I go about preventing this using a try/catch block?
The columns I have are EmployeeID (Unique and PK), FirstName, Surname and JobTitle.
The code I have so far is:
System.Data.SqlClient.SqlConnection connection;
System.Data.SqlClient.SqlDataAdapter adapter;
DataSet DSTestingDataSet;
private void Form1_Load(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
DSTestingDataSet = new DataSet();
connection.ConnectionString = "Data Source=.\\SQLEXPRESS; etc etc";
connection.Open();
string sql = "SELECT * FROM Employee";
adapter = new System.Data.SqlClient.SqlDataAdapter(sql, connection);
adapter.Fill(DSTestingDataSet, "Employee");
connection.Close();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlCommandBuilder builder;
builder = new System.Data.SqlClient.SqlCommandBuilder(adapter);
DataTable dTable = DSTestingDataSet.Tables["Employee"];
DataRow dRow = DSTestingDataSet.Tables["Employee"].NewRow();
dRow["FirstName"] = textBox1.Text;
dRow["Surname"] = textBox2.Text;
dRow["JobTitle"] = textBox3.Text;
DSTestingDataSet.Tables["Employee"].Rows.Add(dRow);
adapter.Update(DSTestingDataSet, "Employee");