System.ArgumentException: Data Source cannot be empty - c#

I am not a programer, I just have a passion for this. I am doing a project which can facilitate my work, but I am facing the error described when connecting to the DB. Here is the code:
public partial class Form1 : Form
{
string dbcon = "#Data Source= KMS.db;Version=3;";
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlcon = new SQLiteConnection(dbcon);
if ((textusername.Text == "") && (textpassword.Text == "") || (textusername.Text == "") || (textpassword.Text == ""))
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Username and / or password are empty!";
}
else
{
try
{
sqlcon.Open();
string query = "SELECT * FROM user WHERE Username = '" + textusername.Text + "' AND Password = '" + textpassword.Text + "'";
SQLiteCommand com = new SQLiteCommand(query, sqlcon);
com.ExecuteNonQuery();
SQLiteDataReader dr = com.ExecuteReader();
int i = 0;
while (dr.Read())
{
i++;
}
if(i == 1)
{
KMS_MainMenu MainMenu = new KMS_MainMenu();
MainMenu.Show();
this.Hide();
}
if(i < 1)
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Invalid Username and / or Password";
textpassword.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Error while logging: " + ex);
}
}
}

Related

How to update SQL Table Using DataGridView Values in C#?

enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}

incorrect syntax near the keyword where c#?

when i run the code this erorr apeared
incorrect syntax near the keyword where c#
public SqlDataReader GetDR(CommandType HandelMode, string SQLStat, List<SqlParameter> Parms)
{
SqlDataReader R = null;
SqlCommand com = new SqlCommand();
SqlConnection Con = GetConn();
try
{
com.CommandText = SQLStat;
com.Connection = Con;
com.CommandType = HandelMode;
if (Parms != null)
{
foreach (SqlParameter P in Parms)
{
com.Parameters.Add(P);
}
}
R = com.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
return null;
}
finally
{
Con.Close();
}
return R;
}
private void pictureBox10_Click_2(object sender, EventArgs e)
{
List<SqlParameter> ParsList = new List<SqlParameter>();
string SelectStatement = "Select ID,Aname,Ename,I_D from " + ScreenMasterTableName;
string Cond = " ID_Co=#ID_Co";
ParsList.Add(new SqlParameter("#ID_Co", FormInfo.ID_Co));
if (S_ID.Text != "")
{
decimal D = 0;
decimal.TryParse(S_ID.Text, out D);
Cond += " and ID=#ID";
ParsList.Add(new SqlParameter("#ID", D));
}
if (S_Aname.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Aname =#Aname";
ParsList.Add(new SqlParameter("#Aname", S_Aname.Text));
}
if (S_Ename.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Ename =#Ename";
ParsList.Add(new SqlParameter("#Ename", S_Ename.Text));
}
if (Cond != "")
Cond = " where " + Cond;
var L = Bus.GetSearchedData(SelectStatement + Cond, ParsList);
dataGridView1.DataSource = L;
label9.Text = L.Count.ToString();
}
Assuming your s_id is filled in you will have a query like this:
where and ID=#ID

C# DataReader error

I looked for a solution to this problem on the forum, but I didn't find one for my problem. On button click, I receive error:
There is already an open DataReader associated with this Connection which must be closed first.
So, I tried to close all DataReaders after using them, I tried to use CommandBehavior, but none of them worked. I tried to use using(MysqlCommand...) but didn't work. What can I do? The strangest thing is that the code is working, but after each button press, I receive that error again. Any ideas?
Please don't flag question as a duplicate, I know that the question exist here but the answer is missing for my problem I guess.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Drawing.Text;
namespace simulator
{
public partial class Simulare : Form
{
public int corect = 0, incorect = 0;
Timer timer;
static string dataA = "SELECT DISTINCT * FROM questions order by rand() limit 1";
public int r1;
public int r2;
public int r3;
public Simulare()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
label1.Text = TimeSpan.FromMinutes(30).ToString("mm\\:ss");
label10.Text = corect.ToString();
label12.Text = incorect.ToString();
//FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
private void simulare_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now;
timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
{
TimeSpan ts = TimeSpan.FromMinutes(30) - (DateTime.Now - startTime);
label1.Text = ts.ToString("mm\\:ss");
if (ts.Minutes == 00 && ts.Seconds == 00)
{
timer.Stop();
MessageBox.Show("Timpul a expirat. Ai picat!");
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
try
{
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalnu = (int)upad["totalno"];
totalnu++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalnu", totalnu);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
}
}
};
timer.Start();
select();
}
private void select()
{
using (ConnConfig.getConnection())
{
MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection());
cmd.CommandType = CommandType.Text;
MySqlDataReader rdra = cmd.ExecuteReader(CommandBehavior.CloseConnection);
try
{
while (rdra.Read())
{
label2.Text = rdra["question"].ToString();
label3.Text = rdra["answer1"].ToString();
label4.Text = rdra["answer2"].ToString();
label5.Text = rdra["answer3"].ToString();
r1 = (int)rdra["option1"];
r2 = (int)rdra["option2"];
r3 = (int)rdra["option3"];
}
rdra.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ConnConfig.closeConn();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int result1 = checkBox1.CheckState == CheckState.Checked ? 1 : 0;
int result2 = checkBox2.CheckState == CheckState.Checked ? 1 : 0;
int result3 = checkBox3.CheckState == CheckState.Checked ? 1 : 0;
using(ConnConfig.getConnection())
{
MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection());
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
try
{
while (rdr.Read())
{
if (checkBox1.Checked == false && checkBox2.Checked == false && checkBox3.Checked == false)
{
MessageBox.Show("Bifati minim o casuta!");
return;
}
else
{
if ((result1 == r1) && (result2 == r2) && (result3 == r3))
{
corect++;
label10.Text = corect.ToString();
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
select();
}
else
{
incorect++;
label12.Text = incorect.ToString();
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
select();
}
if (corect + incorect == 26)
{
int totalalll;
timer.Stop();
button1.Enabled = false;
MySqlCommand upd = new MySqlCommand("select * from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
totalalll = (int)upad["totalall"];
totalalll++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalall=#totalalll where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalalll", totalalll);
Int32 rows = update.ExecuteNonQuery();
}
}
upad.Close();
}
if (corect == 26)
{
MySqlCommand upd = new MySqlCommand("select totalyes from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalda = (Int32)upad["totalyes"];
totalda++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalyes=#totalda where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalda", totalda);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
MessageBox.Show("Bravos");
}
else
{
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalnu = (int)upad["totalno"];
totalnu++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalnu", totalnu);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
MessageBox.Show("Mai invata!");
}
}
}
rdr.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ConnConfig.closeConn();
}
}
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown) return;
if (this.DialogResult == DialogResult.Cancel)
{
e.Cancel = false;
timer.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
class ConnConfig
{
private static string conn = "string connection";
public static MySqlConnection connect;
private ConnConfig()
{
}
public static MySqlConnection getConnection()
{
if(connect !=null){
return connect;
}
else
try{
connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
catch(MySqlException e){
throw new Exception("Cannot connect",e);
}
}
public static void closeConn()
{
connect.Close();
}
public static void openConn()
{
connect.Open();
}
}
Change the getConnection function
public static MySqlConnection getConnection()
{
MySqlConnection connect = null;
try
{
connect = new MySqlConnection(connect);
connect.Open();
return connect;
}
catch (MySqlException e)
{
throw new Exception("Cannot connect", e);
}
}
let all the other codes as it is
The root cause of your exception is that you are executing other queries while you are still iterating over the results of an earlier query.
Bottom line you should not nest queries like you do if you use the same connection for the nested queries.
You are using reader to fetch data from SQLCommand upd.
Then you are reading value.
After that you are using another SqlCommand 'update' to update the result..
Even when you use two different SQLCommands, you are using the same connection. Thats the problem. Use a sperate connection for the second SQLCommand and your problem will be solved.
Try this.
after the line
MessageBox.Show("Timpul a expirat. Ai picat!");
add like
MessageBox.Show("Timpul a expirat. Ai picat!");
MySqlConnection conn1 = ConnConfig.getConnection();
MySqlConnection conn2 = new MySqlConnection();
conn2.ConnectionString = conn1.ConnectionString;
conn2.Open();
and then in the line
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
change like
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", conn1);
and in line
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
change like
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", conn2))

Database is locked. insert operation

I have no idea what to do anymore with this code. I did review the opening and closing of my connections and I think all connections are okay.
I have to tables here that I'm trying to insert data. The imf table and the imf_products table. My goal is as soon as I have inserted data to my imf table I should insert data again to my imf_products.
This 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.SQLite;
namespace Natasha_POS
{
public partial class m2 : Form
{
public SQLiteConnection con = new SQLiteConnection(#"Data Source=default.db");
public m2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (combo_compname.Text.Length <= 0)
{
MessageBox.Show("Please specify the company name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_artname.Text.Length <= 0)
{
MessageBox.Show("Please specify the product name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_color.Text.Length <= 0)
{
MessageBox.Show("Please specify the product color.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_size.Text.Length <= 0)
{
MessageBox.Show("Please specify the product size.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBox8.Text.Length <= 0)
{
MessageBox.Show("Please specify the product price.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (box_numeric.Text.Length <= 0)
{
MessageBox.Show("Please specify the number of products you're acquiring.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dGrid.Rows.Add(combo_artname.Text,
combo_color.Text,
combo_size.Text,
Convert.ToInt32(box_numeric.Value),
Convert.ToInt32( textBox8.Text),
combo_discount.Text,"","",
Convert.ToInt32(combo_artname.SelectedValue),
Convert.ToInt32(combo_color.SelectedValue),
Convert.ToInt32(combo_size.SelectedValue),
Convert.ToInt32(combo_discount.SelectedValue)
);
////new
combo_compname.Text = "--Select Company--";
combo_cat.Text = "--Select Category--";
combo_artname.Text = "--Select Product--";
combo_color.Text = "--Select Color--";
combo_size.Text = "--Select Size--";
textBox8.Clear();
box_numeric.Value = 0;
combo_custno.Focus();
}
}
private void m2_Load(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
box_custname.Text = null;
SQLiteConnection conn1 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt = new DataTable();
conn1.Open();
SQLiteCommand cmd = conn1.CreateCommand();
cmd.CommandText = "SELECT * from customer";
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dt);
combo_custno.DataSource = dt;
combo_custno.ValueMember = "cp_id";
combo_custno.DisplayMember = "customer_no";
combo_custno.Text = "--Select Customer--";
/*IList<string> CustNo = new List<string>();
foreach (DataRow row in dt.Rows)
{
CustNo.Add(row.Field<string>("cp_id"));
}
combo_custno.Items.AddRange(CustNo.ToArray<string>());
combo_custno.AutoCompleteMode = AutoCompleteMode.Suggest;
combo_custno.AutoCompleteSource = AutoCompleteSource.ListItems; */
conn1.Close();
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * from company";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_compname.DataSource = dt2;
combo_compname.ValueMember = "company_id";
combo_compname.DisplayMember = "company_name";
combo_compname.Text = "--Select Company--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT category_id, category_name FROM category";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_cat.DataSource = dt3;
combo_cat.ValueMember = "category_id";
combo_cat.DisplayMember = "category_name";
combo_cat.Text = "--Select Category--";
conn3.Close();
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM colors";
SQLiteDataAdapter adapter4 = new SQLiteDataAdapter(cmd4);
adapter4.Fill(dt4);
combo_color.DataSource = dt4;
combo_color.ValueMember = "color_id";
combo_color.DisplayMember = "color_name";
combo_color.Text = "--Select Color--";
conn4.Close();
SQLiteConnection conn5 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt5 = new DataTable();
conn5.Open();
SQLiteCommand cmd5 = conn5.CreateCommand();
cmd5.CommandText = "SELECT * FROM discount";
SQLiteDataAdapter adapter5 = new SQLiteDataAdapter(cmd5);
adapter5.Fill(dt5);
combo_discount.DataSource = dt5;
combo_discount.ValueMember = "discount_id";
combo_discount.DisplayMember = "discount_name";
combo_discount.Text = "";
conn5.Close();
//this.reportViewer1.RefreshReport();
}
private void combo_custno_SelectedIndexChanged(object sender, EventArgs e)
{
// int x = Convert.ToInt32(combo_custno.Text);
//////////textboxes
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM customer where cp_id = '" + combo_custno.SelectedValue + "'";
SQLiteDataReader dr = cmd4.ExecuteReader();
if (dr.Read())
{
//string fname = Convert.ToString(dr["firstname"]);
//string mname = Convert.ToString(dr["firstname"]);
box_custname.Text = Convert.ToString(dr["firstname"]) + " " + Convert.ToString(dr["middlename"]) + " " + Convert.ToString(dr["lastname"]);
box_mse.Text = Convert.ToString(dr["msediscount"]);
box_nfc.Text = Convert.ToString(dr["nfcdiscount"]);
box_rating.Text = Convert.ToString(dr["rating"]);
box_avcredline.Text = Convert.ToString(dr["available_credit_line"]);
}
conn4.Close();
}
private void combo_cat_SelectedIndexChanged(object sender, EventArgs e)
{
//int x = Convert.ToInt32(combo_cat.Text);
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * FROM product where category_id = '" + combo_cat.SelectedValue+ "'";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_artname.DataSource = dt2;
combo_artname.ValueMember = "product_id";
combo_artname.DisplayMember = "product_name";
combo_artname.Text = "--Select Product--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT * FROM size where category_id = '" + combo_cat.SelectedValue + "'";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_size.DataSource = dt3;
combo_size.ValueMember = "size_id";
combo_size.DisplayMember = "size_name";
combo_size.Text = "--Select Size--";
conn3.Close();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void inserttoSO(string custno)
{
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.Parameters.AddWithValue("#custno", combo_custno.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value);
//cmd.Parameters.AddWithValue("#comment", box_commment.Text);
cmd.CommandText = "INSERT INTO sales_order (customer_no,date) VALUES (#custno,#date)";
cmd.ExecuteNonQuery();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
//inserttoSO(combo_custno.Text);
var results = MessageBox.Show("Are you sure you want to generate this inventory report?",
"Inventory report is successfully made.",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (results == DialogResult.Yes)
{
inserttoSO(combo_custno.Text);
string StrQuery = "";
using (SQLiteConnection conn = new SQLiteConnection(#"Data Source=default.db"))
{
using (SQLiteCommand cmd1 = new SQLiteCommand())
{
cmd1.Connection = conn;
conn.Open();
for (int i = 0; i < dGrid.Rows.Count; i++)
{
/*"INSERT INTO imf_products(imf_id, company_id,product_id, color_id,size_id,price,qty) VALUES (1,1,1,1,1,1,1)";*/
//(SELECT max(imf_id) FROM imf) StrQuery
cmd1.CommandText =
"INSERT INTO orders(salesorder_id, product_id, quantity,price,cash, discount_id) VALUES ((SELECT max(salesorder_id) FROM sales_order),'"
+ dGrid.Rows[i].Cells["product_id"].Value + "', '" + dGrid.Rows[i].Cells["qty"].Value + "', '"
+ dGrid.Rows[i].Cells["price"].Value + "', '" + dGrid.Rows[i].Cells["cash"].Value + "', '"
+ dGrid.Rows[i].Cells["discount_id"].Value + "')";
// cmd.CommandText = StrQuery;
cmd1.ExecuteNonQuery();
MessageBox.Show("Sales report is successfully made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
// conn.Close();
}
}
}
else
{ MessageBox.Show("Inventory report is not made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
}
private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar = 's';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (textBox8.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (textBox8.SelectionStart == 0) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(textBox8.Text, ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (textBox8.SelectionStart != textBox8.Text.Length && e.Handled == false)
{
// '.' or ',' is in the middle
string AfterDotString = textBox8.Text.Substring(textBox8.SelectionStart);
if (AfterDotString.Length > 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(textBox8.Text, ref sepratorChar))
{
int sepratorPosition = textBox8.Text.IndexOf(sepratorChar);
string afterSepratorString = textBox8.Text.Substring(sepratorPosition + 1);
if (textBox8.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
{
e.Handled = true;
}
}
}
}
private bool alreadyExist(string _text, ref char KeyChar)
{
if (_text.IndexOf('.') > -1)
{
KeyChar = '.';
return true;
}
if (_text.IndexOf(',') > -1)
{
KeyChar = ',';
return true;
}
return false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
inserttoSO(combo_custno.Text);
}
}
}

How to make timer event start on button click in aspx website

i am working on an aspx website in which i am using a timer event.
i just want that timer should run when i click a specific button. now timer is running on page load. in Winforms we use timer.Tick() event to do it. but it is not supporting in website.
Can Anyone help me to sort this Out.
Thanks in Advance....
My Code is Here....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
public partial class Expert : System.Web.UI.Page
{
public static BackgroundWorker worker = new BackgroundWorker();
protected void Page_Load(object sender, EventArgs e)
{
int id;
id = Int32.Parse(Request.QueryString["id"]);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd;
rd = new SqlCommand("Select * from ExpertChat where id=" + id, con).ExecuteReader();
rd.Read();
Image1.ImageUrl = rd["image1"].ToString();
Label8.Text = rd["image1"].ToString();
//Image3.ImageUrl = rd["image1"].ToString();
Label1.Text = rd["SName"].ToString();
Label2.Text = rd["Skills"].ToString();
Label5.Text = rd["rate"].ToString();
Label3.Text = rd["ReviewCount"].ToString();
Label4.Text = rd["Title"].ToString();
Label6.Text = rd["ReviewCount"].ToString();
Label7.Text = rd["Title"].ToString();
Label9.Text = rd["Qualification"].ToString();
Label10.Text = rd["MyServices"].ToString();
Label11.Text = rd["other"].ToString();
Label14.Text = rd["IsLoggedIn"].ToString();
int x = Int32.Parse(rd["IsLoggedIn"].ToString());
if (x == 1)
{
Image2.ImageUrl = "~/online.png";
}
else
{
Image2.ImageUrl = "~/offline.png";
}
rd.Close();
if (Session["User"] == "User")
{
SqlDataReader rd1 = new SqlCommand("Select funds from signup where email='" + Session["email"].ToString() + "'", con).ExecuteReader();
rd1.Read();
Label13.Text = rd1["funds"].ToString();
}
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void SendButton_Click(object sender, EventArgs e)
{
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, "yash", DateTime.Now.ToShortTimeString(), NewMessageTextBox.Text);
TextBox1.Text = TextBox1.Text + Environment.NewLine + message;
// Calling the DoWork Method Asynchronously
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", "document.getElementById('" + NewMessageTextBox.ClientID + "').value = '';", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
if (worker.IsBusy != true)
{
worker.RunWorkerAsync(new string[] { message, Label3.Text });
}
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
string[] args = e.Argument as string[];
string value = args[0];
string id = args[1];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("Update Chat set Data=#message,Updated1=1 where id=" + Int32.Parse(id), con);
cmd.Parameters.AddWithValue("#message", value);
cmd.ExecuteNonQuery();
con.Close();
}
protected void ChatTextTimer_Tick(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
//if (second1.Visible)
//{
// SqlDataReader rd7 = new SqlCommand("Select IsApproved from Chat where id=" + Int32.Parse(Label2.Text) + "'", con).ExecuteReader();
// rd7.Read();
// string str3 = rd7["IsApproved"].ToString();
// rd7.Close();
// if (str3 == "Approved")
// {
// second1.Visible = false;
// }
// else if (str3 == "Canceled")
// {
// second1.Visible = false;
// second3.Visible = true;
// }
//}
//else
//{
int x1 = 0;
SqlDataReader rd;
rd = new SqlCommand("Select UserInitial,Updated from Chat where id =" + Int32.Parse(Label3.Text), con).ExecuteReader();
rd.Read();
string str;
int i;
i = Int32.Parse(rd["Updated"].ToString());
if (i == 1)
{
str = rd["UserInitial"].ToString();
rd.Close();
x1 = x1 + 1;
TextBox1.Text = TextBox1.Text + Environment.NewLine + str;
SqlCommand
cmd = new SqlCommand("Update Chat set Updated=0 where id=" + Int32.Parse(Label3.Text), con);
cmd.ExecuteNonQuery();
}
else
{
rd.Close();
}
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Session["User"] != "User")
{
Response.Redirect("signin.aspx");
}
else
{
if (Int32.Parse(Label13.Text) < 20)
{
Response.Redirect("Payment.aspx");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd = new SqlCommand("Select Booked,email from ExpertChat where id=" + Request.QueryString["id"].ToString(), con).ExecuteReader();
rd.Read();
int x = Int32.Parse(rd["Booked"].ToString());
string str = rd["email"].ToString();
rd.Close();
if (x == 0)
{
//second1.Visible = true;
SqlDataReader mRead1, mRead3, mRead4;
mRead1 = new SqlCommand("insert into chat (ExpertName,UserName,rate,Data,Date,UserInitial) Values ('" + str + "','" + Session["SName"] + "','" + Label5.Text + "','Hello','" + DateTime.Now.ToShortDateString() + "','yash')", con).ExecuteReader();
mRead1.Close();
mRead3 = new SqlCommand("Update ExpertChat Set Booked=1 where SName='" + Label1.Text + "'", con).ExecuteReader();
mRead3.Close();
mRead4 = new SqlCommand("Select top 1 id from Chat where ExpertName='" + str + "' Order by id desc", con).ExecuteReader();
mRead4.Read();
int y = Int32.Parse(mRead4["id"].ToString());
mRead4.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "button1Clicked();", true);
ChatTextTimer.Enabled = true;
second3.Visible = false;
second1.Visible = false;
second2.Visible = false;
int id;
id = y;
Label3.Text = id.ToString();
SqlDataReader rd1 = new SqlCommand("Select ExpertName from Chat where id=" + y, con).ExecuteReader();
rd1.Read();
string str23 = rd1["ExpertName"].ToString();
rd1.Close();
SqlDataReader rd3;
rd3 = new SqlCommand("Select * from ExpertChat where email='" + str23 + "'", con).ExecuteReader();
rd3.Read();
string str2;
str2 = rd3["email"].ToString();
Label1.Text = rd3["rate"].ToString();
Image3.ImageUrl = rd3["image1"].ToString();
Label12.Text = rd3["rate"].ToString();
rd3.Close();
con.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
//second2.Visible = true;
}
}
}
}
}
i want to run it when ImageButton1_Click event Fired....
If you're using Visual Studio 2010 up (correct me if I have my versions wrong) you should have access to Intellisense. You can use this to see all of your available methods.
Timer.Start()
http://msdn.microsoft.com/en-us/library/system.timers.timer.start(v=vs.110).aspx

Categories

Resources