I have a WFA C# code which helps to insert data into the SQL table and reset the fields once saved, now I want to avoid duplicate values in the Table, want a message box if data already exists and let update it, if data doesn't exist then want to insert it, kindly help(Add code required). below is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
namespace Dispatch_Tracker
{
public partial class DispatchTracker : Form
{
public DispatchTracker()
{
InitializeComponent();
}
string connection = "Data Source=WN7-4WVX1BS;" + "Initial Catalog=DispatchDB;Persist Security Info=True;" + "User ID=sa;" + "Password= ***";
private void Save_Click(object sender, EventArgs e)
{
if (DispatcherName.Text == "")
{
MessageBox.Show("Would you like to Lose out on Productivity?\nPlease select the Dispatcher name.");
DispatcherName.Focus();
}
else if (DispatchNumber.Text == "")
{
MessageBox.Show("Did you really process a Dispatch?\nI don't see a Dispatch Number.");
DispatchNumber.Focus();
}
else if (DPSType.Text == "")
{
MessageBox.Show("Did You Just Forget Something?\nPlease Enter the DPS Type");
DPSType.Focus();
}
else if (QG.Text == "")
{
MessageBox.Show("Please select the Queue which the DPS belongs to.");
QG.Focus();
}
else
{
dateTimePickerDT.Value = System.DateTime.Now;
string sDispatcher = DispatcherName.Text;
string sDPSNum = DispatchNumber.Text;
string sDPSType = DPSType.Text;
DateTime dtDT = dateTimePickerDT.Value;
string sQueue = QG.Text;
string query = "INSERT INTO dps_data(DispatcherName, DispatchNumber, DPSType, DateTime, Queue)" +"VALUES( @Dispatcher, @DPSNum, @DPSType, @DT, @Queue)";
SqlConnection conn = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.Parameters.Add(new SqlParameter("@Dispatcher", sDispatcher));
cmd.Parameters.Add(new SqlParameter("@DPSNum", sDPSNum));
cmd.Parameters.Add(new SqlParameter("@DPSType", sDPSType));
cmd.Parameters.Add(new SqlParameter("@DT", dtDT));
cmd.Parameters.Add(new SqlParameter("@Queue", sQueue));
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Data Added Successfully");
}
else
{
MessageBox.Show("Error in Adding Data");
}
conn.Close();
DispatchNumber.Text = String.Empty;
DPSType.Text = String.Empty;
QG.Text = String.Empty;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void DispatcherName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void QG_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Edited: Code Blocks added