This simple Winforms program reads the input from a serial connection. I'm trying to send the received data to a local database for later retrieval.
However, the data doesn't seem to be inserted into the database table correctly since it keeps being empty. I receive no errors when running the program, and everything else works just fine. Below is the program code
public partial class Form1 : Form
{
private SerialPort myPort;
private string dataIn;
private DateTime dt;
private static string cnString = Properties.Settings.Default.Database1ConnectionString;
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True
private SqlConnection dbConnection = new SqlConnection(cnString);
private SqlDataAdapter adapter = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
myPort.DataReceived += MyPort_DataReceived;
try
{
myPort.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void MyPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(display_dataevent));
dataIn = myPort.ReadLine();
dt = DateTime.Now;
dbConnection.Open();
using (var insertCmd = new SqlCommand(@"INSERT INTO Measurements (Distance,DateTime) VALUES (@Distance,@DateTime)", dbConnection))
{
insertCmd.Parameters.Add("@Distance", SqlDbType.VarChar).Value = dataIn;
insertCmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = dt;
insertCmd.ExecuteNonQuery();
}
dbConnection.Close();
}
private void display_dataevent(object sender, EventArgs e)
{
dt = DateTime.Now;
string time = dt.Hour + ":" + dt.Minute + ":" + dt.Second;
textBox1.AppendText(time + "\t\t\t" + dataIn + "\n");
}
}
}
Everything works now. The connection string was to blame. I don't quite understand how since I've only created the one database, so I don't know where from it got the incorrect string.