Displaying on different times - c#

This is for my timer
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm();
}
private void medicineAlarm()
{
DataTable dt = new DataTable();
dt = database.getSchedule();
string AMTime;
string PMTime;
string NNTime;
foreach (DataRow row in dt.Rows)
{
AMTime = row["AMIntake"].ToString();
PMTime = row["PMIntake"].ToString();
NNTime = row["NNIntake"].ToString();
if (AMTime == timeNow || PMTime == timeNow || NNTime == timeNow)
{
MessageBox.Show("Drink Medicine");
}
}
}
How can i show the message even if i am running the program? Hope you can help me. This is inside my form_load
private void Form1_Load(object sender, EventArgs e)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(this.timer_tick);
timer.Start();

The medicineAlarm() method does not have any access to the timeNowvariable that you are setting up in the timer_tick() event handler. I suggest you pass the variable in:
private void timer_tick(object sender, EventArgs e)
{
string timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}
private void medicineAlarm(string timeNow)
{
DataTable dt = database.getSchedule();
foreach (DataRow row in dt.Rows)
{
foreach(var label in new [] {"AM", "PM", "NN"})
if (row[label + "Intake"].ToString() == timeNow)
{
MessageBox.Show("Drink Medicine");
return;
}
}
}

I don't think your code compiles at all since the variable string timeNow = ""; is declared in event handler and doesn't exists in your method body. You may want to pass it to the method like
private void medicineAlarm(string timeNow)
{
You then call it
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}

Related

Cant write any data into my SQLite database

private void comboBox9_SelectedIndexChanged(object sender, EventArgs e)
{
finish_day = Convert.ToInt32(comboBox9.Text);
}
private void comboBox10_SelectedIndexChanged(object sender, EventArgs e)
{
finish_month = Convert.ToInt32(comboBox10.Text);
}
private void comboBox11_SelectedIndexChanged(object sender, EventArgs e)
{
finfish_year = Convert.ToInt32(comboBox11.Text);
}
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
begin_year = Convert.ToInt32(comboBox6.Text);
}
private void comboBox7_SelectedIndexChanged(object sender, EventArgs e)
{
begin_month = Convert.ToInt32(comboBox7.Text);
}
private void comboBox8_SelectedIndexChanged(object sender, EventArgs e)
{
begin_day = Convert.ToInt32(comboBox8.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void showdata(object sender, EventArgs e)
{
int changdu = from_bs_2.Length;
if (changdu > 50)
{
chushihua++;
string fro;
string[] parm = new string[6];
textBox1.Text += from_bs_2;
fro = from_bs_2;
parm = fro.Split('\n');
string path = "C:\\Users\\COM\\Desktop\\data_logging.txt";
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
for (int a = 0; a < 4; a++)
{
string[] zhongjian = new string[23];
zhongjian = parm[a].Split(';');
// textBox1.Text += zhongjian;
for (int keai = 0; keai < 23; keai++)
{
current[a, keai] = Convert.ToDouble(zhongjian[keai]);
sw.Write(current[a, keai]); sw.Write(';');
}
sw.WriteLine('/');
}
string[] zhongjian_2 = new string[23];
zhongjian_2 = parm[5].Split(';');
for (int m = 0; m < 23; m++) //
{
volatge[m] = Convert.ToDouble(zhongjian_2[m]);
sw.Write(volatge[m]); sw.Write(';');
}
sw.WriteLine('/');
DateTime dt = DateTime.Now; //strong text
int y = dt.Year; //
int yue = dt.Month; //
int d = dt.Day; //
int h = dt.Hour; //
int n = dt.Minute; //
textBox1.Text += y;
textBox1.Text += "-";
textBox1.Text += yue;
textBox1.Text += "-";
textBox1.Text += d;
textBox1.Text += "-";
textBox1.Text += h;
textBox1.Text += ":";
textBox1.Text += n;
textBox1.Text += "-";
textBox1.Text += "data logging times";
textBox1.Text += chushihua;
sw.Write(y); sw.Write("-"); sw.Write(yue); sw.Write("-"); sw.Write(d);
sw.Write("-"); sw.Write(h); sw.Write(":"); sw.Write(n); sw.WriteLine('/');
sw.Close();
fs.Close();
//////////////////time/////////////////////////////
string info = "INSERT INTO Logging_Data_2 (Time,Number,Power1,Power2,Power3,Power4,Power5,Power6,Power7,Power8,Power9,Power10,Power11,Power,Power12,Power13,Power14,Power15,Power16,Power17,Power18,Power19,Power20,Power21,Power22,Power23) values ('a',1,current[0, 0],current[0, 1],current[0, 2],current[0, 3],current[0, 4],current[0, 5],current[0, 6],current[0, 7],current[0, 8],current[0, 9],current[0, 10],current[0, 11],current[0, 12],current[0, 13],current[0, 14],current[0, 15],current[0, 16],current[0, 17],current[0, 18],current[0, 19],current[0, 20],current[0, 21],current[0, 22])";
using (System.Data.SQLite.SQLiteConnection connection = new System.Data.SQLite.SQLiteConnection("data source=logging_data.db"))
{
// connection.Open();
// using (DbTransaction transaction = connection.BeginTransaction())
// {
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(connection))
{
connection.Open();
command.CommandText = info;
//*emphasized text*command.ExecuteNonQuery();
}
// transaction.Commit();
// }
}
from_bs_2 = "";
if (textBox1.Text.Length > 1500)
{
textBox1.Text = "";
}
}
}
I am wirting a super simple file, get the data from arduino though serial ports, and than if i get data, first i log them in a txt file, and then I need to send them into a database for future calculation. therefore I installed the SQLite, and write caode in this, but when i test it, I can log data to txt fime, but nothing in my database.
I set up a database named logging_data, and the table is Logging_data_2, when I find I cant log any data to database, i just let the time be 'a', number be 1,but it still doesnt work. ask for help, thankyou!

How to plot graphs with data from a SerialPort with multiple sensors

I need to plot data from sensors of pH, Temperature and Humidity, the data is sent as a matrix from arduino to PC through the serial port.
I can show the data in a TextBox, but when I try to plot the data, it doesn't work (I don't know how to do it).
I just can plot the data when is not a matrix and it's data from just one sensor.
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.Threading.Tasks;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
namespace grafik1
{
public partial class Form1 : Form
{
private SerialPort sensport;
private DateTime datetime;
private string data;
private string data2;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = SerialPort.GetPortNames();
timer1.Start();
}
double rt = 0;
Boolean i = false;
private void timer1_Tick(object sender, EventArgs e)
{
rt = rt + 0.1;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
sensport.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
MessageBox.Show("Error");
}
else
{
sensport = new SerialPort();
sensport.BaudRate = int.Parse(comboBox2.Text);
sensport.PortName = comboBox1.Text;
sensport.Parity = Parity.None;
sensport.DataBits = 8;
sensport.StopBits = StopBits.One;
sensport.Handshake = Handshake.None;
sensport.DataReceived += sensport_DataReceived;
try
{
sensport.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
void sensport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (i == false)
{
rt = 0;
i = true;
}
data = sensport.ReadLine();
this.chart1.Series["Data1"].Points.AddXY(rt, data);
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Day + "/" + datetime.Month + "/" + datetime.Year + "\t" + datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
txtData.AppendText(time + "\t" + data + "\n");
}
private void button2_Click(object sender, EventArgs e)
{
string directorio = textBox1.Text;
if (directorio == "")
{
MessageBox.Show("Error");
}
else {
try
{
string kayıtyeri = #"" + directorio + "";
this.chart1.SaveImage(("+kayityeri+"), ChartImageFormat.Png);
MessageBox.Show("Grafica guardada en " + kayıtyeri);
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
sensport.Close();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\MARIO GONZALEZ\Google Drive\VisualStudio\Arduino0_1\DATA";
string filename = "arduinoRTPv1.xls";
System.IO.File.WriteAllText(pathfile + filename, txtData.Text);
MessageBox.Show("Data saved");
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void chart1_Click(object sender, EventArgs e)
{
}
}
}
Let's assume you have prepared your chart, maybe like this:
chart1.Series.Clear();
chart1.Series.Add("ph");
chart1.Series.Add("Temp");
chart1.Series.Add("Hum");
chart1.Series["ph"].ChartType = SeriesChartType.Line;
chart1.Series["Temp"].ChartType = SeriesChartType.Line;
chart1.Series["Hum"].ChartType = SeriesChartType.Line;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY2.Title = "Temp";
chart1.ChartAreas[0].AxisY2.Maximum = 100;
Now you can add a string that contains some data blocks as shown in the comments..
string data = "7.5 23.8 67 \n8.5 23.1 72 \n7.0 25.8 66 \n";
..like this:
var dataBlocks = data.Split('\n');
foreach (var block in dataBlocks)
{
var numbers = block.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
// rt += someTime; (*)
for (int i = 0; i < numbers.Length; i++)
{
double n = double.NaN;
bool ok = double.TryParse(numbers[i], out n);
if (ok) chart1.Series[i].Points.AddXY(rt, n);
else
{
int p = chart1.Series[i].Points.AddXY(rt, 0);
chart1.Series[i].Points[p].IsEmpty = true;
Console.WriteLine("some error message..");
}
}
}
I have modified the data a little to show the changes a little better..
Note that I left out the counting up of your timer rt, which is why the chart shows the points with indexed x-values. For a real realtime plot do include it maybe here (*) !
If you keep adding data your chart will soon get rather crowded.
You will then either have to remove older data from the beginning or at least set a minimum and maximum x-values to restrict the display to a reasonably number of data points and or turn on zooming!
See here here and here for some examples and discussions of these things!

DataGridView column DateTimePicker in vb.net C#

I am using a DataGridView inner DateTimePicker, but it is not working properly.
It can only select the year or month and the calendar control is closed.
How do I to select the year & month & date?
Try this code (c# code)
DateTimePicker dtp = new DateTimePicker(); //DateTimePicker
Rectangle _Rectangle;
public Form2()
{
InitializeComponent();
dataGridView2.Controls.Add(dtp);
dtp.Visible = false; //
dtp.Format = DateTimePickerFormat.Custom; //2010-08-05
dtp.TextChanged += new EventHandler(dtp_TextChange);
}
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
switch (dataGridView2.Columns[e.ColumnIndex].Name)
{
case "dateAchatDataGridViewTextBoxColumn1":
_Rectangle = dataGridView2.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //
dtp.Size = new Size(_Rectangle.Width, _Rectangle.Height); //
dtp.Location = new Point(_Rectangle.X, _Rectangle.Y); //
dtp.Visible = true;
break;
}
}
private void dtp_TextChange(object sender, EventArgs e)
{
dataGridView2.CurrentCell.Value = dtp.Text.ToString();
}
private void dataGridView2_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
dtp.Visible = false;
}
private void dataGridView2_Scroll(object sender, ScrollEventArgs e)
{
dtp.Visible = false;
}
This is answer:
public partial class Form1 : Form
{
private DateTimePicker cellDateTimePicker = new DateTimePicker();
DateTimePicker[] sp = new DateTimePicker[100];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt=new DataTable();
dt.Columns.Add(new DataColumn("Start-Date", typeof(DateTime)));
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
sp[e.RowIndex] = new DateTimePicker();
if (dataGridView1.Columns[e.ColumnIndex].Name == "Start-Date")
{
this.cellDateTimePicker = sp[e.RowIndex];
this.cellDateTimePicker.Format = DateTimePickerFormat.Time;
this.cellDateTimePicker.Name = "sp[" + e.RowIndex + "]";
// this.cellDateTimePicker.ValueChanged += new EventHandler(cellDateTimePickerValueChanged);
this.cellDateTimePicker.Visible = true;
this.cellDateTimePicker.CustomFormat = "dd/MM/yyyy";
this.cellDateTimePicker.Format = DateTimePickerFormat.Custom;
this.dataGridView1.Controls.Add(cellDateTimePicker);
System.Drawing.Rectangle tempRect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
cellDateTimePicker.Location = tempRect.Location;
cellDateTimePicker.Width = tempRect.Width;
dataGridView1.Columns[0].DefaultCellStyle.Format = "MM'/'dd'/'yyyy";
this.cellDateTimePicker.Visible = true;
}
}
}

Display all values of Hashtable through button

Okay so I'm trying to display multiple values in hashtable through my button. But it keeps on showing me the first value but not the others.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
Info.Add(a,b);
label4.Text = a + " " + b;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DictionaryEntry DE in Info)
{
label4.Text = ""+ DE.Key +DE.Value; //this only shows the first added value. How do I show the remaining values?
}
}
This is because each iteration of the loop replaces the previous value in the text. You can fix this by clearing out the text before going into the loop, and using += instead of =:
label4.Text += " "+ DE.Key +DE.Value
A better approach would be to use string.Join for this:
private void button3_Click(object sender, EventArgs e) {
label4.Text = string.Join(
", "
, Info.Select(p => string.Format("{0}-{1}", p.Key, p.Value))
);
}
I recommend you don't keep changing label4.Text in the loop, but build a string in the loop and change it once at the end. Something like:
StringBuilder allEntries = new StringBuilder();
foreach (DictionaryEntry DE in Info)
{
allEntries.Append(DE.Key);
allEntries.Append(DE.Value);
}
label4.Text = allEntries.ToString();
[I edited an earlier version of the code that didn't compile.]
KC

For some reason it does not perform the timer2_tick function

The program is supposed to call start timer1 when a button is clicked, timer1 is 17secs long. Then in timer1 it is supposed to start timer2, which is 8secs long. For some reason it does not perform the timer2_tick function.
private void timer1_Tick(object sender, EventArgs e)
{
string[] ProxList = File.ReadAllLines("C:\\Prox.txt");
string[] s = new string[4];
WinInetInterop.SetConnectionProxy(ProxList[p]);
if (p > 3273)
p = 0;
s[0] = textBox1.Text;
s[1] = textBox2.Text;
s[2] = textBox3.Text;
s[3] = textBox4.Text;
try
{
webBrowser1.Navigate(s[txtBxNum]);
timer2.Start();
label1.Text = "Current Link: " + s[txtBxNum].ToString();
label2.Text = "Current IP: " + ProxList[p].ToString();
txtBxNum++;
if (txtBxNum > 3)
txtBxNum = 0;
}
catch { }
p++;
}
private void timer2_Tick(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
webBrowser1.Document.GetElementById("skip_ad_button").InvokeMember("click");
}
catch { }
}

Categories