Connection was not closed. The connection's current state is open - c#

How to fix this problem? I don't know why this error occur when I already add Clode().
The error will go here:
public void existType()
{
try
{
con.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, con);
da.Fill(ds, "tblRoomType");
int counter = 0;
string tabletype = "tblRoomType";
if (counter < ds.Tables[tabletype].Rows.Count)
{
string type = ds.Tables[tabletype].Rows[counter]["Type"].ToString();
if (type == txtRoomType.Text)
{
editRoomType(); //There will be no error if I remove this and include the MessageBox below.
MessageBox.Show("Successfully Edited", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("This " + txtRoomType.Text + " is already exist.", "EXIST", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else //Remove this will remove the error
{
addRoomType();
MessageBox.Show("Successfully Added", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//to here
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This are the code of editRoomType() and addRoomType():
public void addRoomType()
{
con.Open();
string addtypequery = "INSERT INTO tblRoomType VALUES ('" + this.typeid + "','" + txtRoomType.Text + "','" + txtRoomRate.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "','" + txtMaxOcc.Text + "')";
cmd = new OleDbCommand(addtypequery, con);
cmd.ExecuteNonQuery();
con.Close();
loadRoomType();
txtRoomType.ReadOnly = false;
txtRoomType.Enabled = false;
txtRoomRate.Enabled = false;
txtMaxOcc.Enabled = false;
txtExtraCharge.Enabled = false;
txtCancelFee.Enabled = false;
btnAddRoomType.Enabled = false;
txtRoomType.Clear();
txtRoomRate.Clear();
txtMaxOcc.Clear();
txtExtraCharge.Clear();
txtCancelFee.Clear();
}
public void editRoomType()
{
con.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, con);
cmd.ExecuteNonQuery();
con.Close();
}
The existType() will be go here:
private void btnAddRoomType_Click(object sender, EventArgs e)
{
if (txtRoomType.Text != "" || txtRoomRate.Text != "" || txtExtraCharge.Text != "" || txtCancelFee.Text != "" || txtMaxOcc.Text != "")
{
existType();
}
else
{
MessageBox.Show("Please fill in the space provided","OOPPSS!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

The error is because you call con.Open in existType, then you either call addRoomType or editRoomType, both of which call con.Open again before you call con.Close in existType. Calling con.Open on an already open connection will throw the error you are seeing.
You can either remove the calls to con.Open/con.Close inside of the addRoomType or editRoomType and only call them in existType, or use local connections for each method, like so:
public void existType()
{
try
{
using (var conn = new SqlConnection())
{
conn.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, conn);
da.Fill(ds, "tblRoomType");
}
//rest of code
}
}
public void editRoomType()
{
using (var conn = new SqlConnection())
{
conn.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, conn);
cmd.ExecuteNonQuery();
}
}
Note that you don't have to call Close since the using statement will do that for you.

Try like this -
try
{
con.Open();
.......
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Open();
}
}

Related

How to insert a different selectedindex combobox value into database?

In my project i have a countries combobox (PaysCmBx0) that is filled from countries database table [Pays] column [pays], what i want to do is when i select a country in the combobox it insert the Alpha country code token from the Alpha country code column [Alpha2] in another table (exemple : United-states = US).
so when i select a country from the combobox it does nothing it's intserting the same value.
My table look like this:
[Aplha2] [Pays]
GB United Kingdom
IM Isle of Man
TZ United Republic Of Tanzania
US United States
BF Burkina Faso
UY Uruguay
UZ Uzbekistan
here's my code :
void Fillcombo()
{
string Query = "SELECT * FROM Pays";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd.ExecuteReader();
while (myRead.Read())
{
string sName = myRead["Pays"].ToString();
PaysCmBx0.Items.Add(sName);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void AddBtn_Click(object sender, EventArgs e)
{
try
{
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + TypeAdrCmBx.Text+ "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
SqlDataReader Read;
try
{
Read = cmd.ExecuteReader();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PaysCmBx0_SelectedIndexChanged(object sender, EventArgs e)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
string Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
thanks every one i fund a solutions for this :
i create a function that gets the country code corresponding to what's selected in the combobox:
private string get_code_pays(string nom_pays)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
string Code_Pays="";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
return Code_Pays;
}
and then call my funtion with the parameter in my insert:
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + A + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + get_code_pays( this.PaysCmBx0.Text) + "')";

I Cannot Update A Table in Ms Access with C#. No Error Message

I want to update a table in Ms Access whenever I click save button in C#. So, whenever I add a new value into the [Checkin] table, the [kamar] table will update itself. But, [kamar] table doesn't want to update. There is no error message.
Here is my code:
private void simpan()
{
string noreg = noregBox.Text;
string noktp = noktpCBox.Text;
string nokamar = nokamarCBox.Text;
string tglCheckin = txttanggalCheckin.Value.ToString("MM/dd/yyyy");
decimal dp = Convert.ToDecimal(dpBox.Text);
if (nokamar.Equals("") || noreg.Equals(""))
{
MessageBox.Show("Data tidak boleh kosong");
return;
}
try
{
cmdCheckin = new OleDbCommand("insert into Checkin (no_reg_in,tgl_checkin,no_ktp,no_kamar,dp_kamar) values ('" + noreg + "', '" + tglCheckin + "', '" + noktp + "', '" + nokamar + "', '" + dp + "')", cn);
cmdCheckin.ExecuteNonQuery();
MessageBox.Show("Data berhasil disimpan");
nokamarCBox.Text = "";
noktpCBox.Text = "";
namatamuBox.Clear();
jktamuCBox.Text = "";
telptamuBox.Clear();
alamatBox.Clear();
kelaskamarBox.Clear();
biayaBox.Clear();
dpBox.Clear();
muat();
}
catch (OleDbException error)
{
MessageBox.Show(Convert.ToString(error));
return;
}
}
private void perbarui()
{
string nokamar = nokamarCBox.Text;
string kelas = kelaskamarBox.Text;
try
{
cmdCheckin = new OleDbCommand("update kamar set status = 0 where no_kamar = '" + nokamar + "'", cn);
cmdCheckin.ExecuteNonQuery();
dtCheckin.Clear();
daCheckin.Fill(dtCheckin);
}
catch (Exception err)
{
MessageBox.Show("Data gagal diubah, error" + err);
}
}
private void button2_Click(object sender, EventArgs e)
{
simpan();
perbarui();
muat();
}
button2 is save button. Thank you. Sorry for my bad English
First you set:
nokamarCBox.Text = "";
Then:
string nokamar = nokamarCBox.Text;
Thus, no nokamar is to update.

Trouble in C# inventory system update button

I have a problem in the form of my inventory system. Well it worked perfectly when one textbox was involved. But when there are 2 or more textbox involve it shows errors specifically: Truncated incorrect DOUBLE value: 'Knooks and Cranies'.
(Knooks and Cranies is an example of a supplier i inputted.)
I don't really know what's wrong because this is the 1st time I've encountered this error.
here's my code:
namespace SupplyRequestAndInventoryManagementSystem
{
public partial class DI_Assets : Form
{
connection con = new connection();
MySqlCommand cmd;
MySqlDataReader reader;
public DI_Assets()
{
InitializeComponent();
}
//load data from database
private void DI_Assets_Load(object sender, EventArgs e)
{
loadDepartment();
}
//checker
private void ListDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListDelivery.SelectedItems.Count > 0)
{
ListViewItem itm = ListDelivery.SelectedItems[0];
lblAssetIDChecker.Text = itm.SubItems[4].Text;
}
}
//load data from supplier
private void btnSearch_Click(object sender, EventArgs e)
{
loadtbl();
}
//add button
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to add new Delivery Information?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" || txtProdName.Text == "" || txtProdBrand.Text == "" || txtQty.Text == "" || DTPReceived.Text == "")
{
MessageBox.Show("Don't leave blanks!");
}
else
{
con.Close();
cmd = new MySqlCommand("Select * from deliver_mat where Del_MSupplier ='" + SuppNameCombo.Text + "' and Del_MName='" + txtProdName.Text + "' and Del_MBrand ='" + txtProdBrand.Text + "' and Del_MQty= '" + txtQty.Text + "' and Del_MReceived='" + DTPReceived.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Delivery Information already exist, sepcify a new one!");
}
else
{
addSection();
MessageBox.Show("Delivery Information successfully added!");
loadtbl();
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
}
else
{
MessageBox.Show("Adding new Delivery Information has been cancelled!");
}
}
//update button
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to update the section?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" && txtProdName.Text == "" && txtProdBrand.Text == "" && txtQty.Text == "" && DTPReceived.Text == "")
{
MessageBox.Show("Please choose section to be updated!");
}
else
{
updateSection();
MessageBox.Show("Section has been successfully updated!");
loadtbl();
SuppNameCombo.Text = "";
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
else
{
MessageBox.Show("Updating section has been cancelled!");
}
}
//----------------------------------------------------------------------------------------------
//Retrieving Data from DB to listview
void loadtbl()
{
con.Close();
DataTable table = new DataTable();
cmd = new MySqlCommand("Select * from deliver_assets where Del_ASupplier = '" + SuppNameCombo.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
ListDelivery.Items.Clear();
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["Del_AName"].ToString());
item.SubItems.Add(reader["Del_ABrand"].ToString());
item.SubItems.Add(reader["Del_AReceived"].ToString());
item.SubItems.Add(reader["Del_AQty"].ToString());
item.SubItems.Add(reader["Del_aID"].ToString());
item.SubItems.Add(reader["Del_ASupplier"].ToString());
ListDelivery.Items.Add(item);
}
}
//Load Data to combo box
void loadDepartment()
{
con.Close();
DataTable table5 = new DataTable();
cmd = new MySqlCommand("Select Supp_Name from supply", con.con);
con.Open();
reader = cmd.ExecuteReader();
table5.Load(reader);
foreach (DataRow row in table5.Rows)
{
SuppNameCombo.Items.Add(row["Supp_Name"]);
}
}
//add function
void addSection()
{
con.Close();
cmd = new MySqlCommand("insert into deliver_assets(Del_AName, Del_ABrand, Del_AReceived, Del_AQty, Del_Asupplier) values('" + txtProdName.Text + "', '" + txtProdBrand.Text + "', '" + DTPReceived.Text + "', '" + txtQty.Text + "', '" + SuppNameCombo.Text + "')", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
//update function
void updateSection()
{
con.Close();
cmd = new MySqlCommand("update deliver_assets set Del_ASupplier ='" + SuppNameCombo.Text + "' and Del_AName ='" + txtProdName.Text + "' and Del_ABrand ='" + txtProdBrand.Text + "' and Del_AQty ='" + txtQty.Text + "' and Del_AReceived ='" + DTPReceived.Text + "' where Del_aID ='" + lblAssetIDChecker.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
}
}
Your code contains many errors that should be avoided in handling a database task:
Use of global variables for disposable object (in particular a
MySqlConnection)
No use of parameters
Incorrect syntax for the Update statement
Use of incorrect methods to Execute insert/update queries
Trying to use a do-it-all method to establish a connection (related
to first)
Thinking that a column with a specific datatype will happily accept a string as its value
To just give an example I will try to rewrite the Update code
//update function
void updateSection()
{
string cmdText = #"update deliver_assets
set Del_ASupplier =#sup.
Del_AName = #name,
Del_ABrand = #brand
Del_AQty = #qty
Del_AReceived = #recv
where Del_aID = #id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
cmd.Parameters.Add("#sup", MySqlDbType.VarChar).Value = SuppNameCombo.Text;
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtProdName.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = txtProdBrand.Text;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = Convert.ToDouble(txtQty.Text);
cmd.Parameters.Add("#recv", MySqlDbType.VarChar).Value = DTPReceived.Text;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = Convert.ToInt32(lblAssetIDChecker.Text);
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
}
}
Note that I can't be sure about the correct datatype of your columns. You should create the parameter with the DataType compatible for your column changing the MySqlDbType values shown in the example above.

Local database not refreshing after updating data from C#

I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}
I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

Error on Looping mssql statment using c# windows form

I am trying to check whether database have the following data before making decision to update or insert but current i have a problem not able to loop through as it only execute once.
//It is suppose to loop based on the value in account.devices.Count --> last tried with 10 values
for (int z = 0; z < account.devices.Count; ) have 10 data inside account.device.Count
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
myReader.Close();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
z++;
}
Thanks in advance
Update working codes
try
{
for (int z = 0; z < account.devices.Count; )
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
myReader.Close();
z++;
}
}
catch(Exception e)
{
this.listBox1.BeginInvoke((MethodInvoker)delegate()
{
listBox1.Items.Add(DateTime.Now.ToString("hh:mm:ss tt") + " [DB Insert] " + e.ToString());
this.listBox1.SelectedIndex = listBox1.Items.Count - 1;
this.listBox1.SelectedIndex = -1;
});
}

Categories