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

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

Related

How can i insert changes from datagridview to database?

As you can read from header, i had a problem with insert from datagridview. Here code of my shiny probram:
namespace LibrarianApp
{
public partial class Start : Form
{
public Start()
{
InitializeComponent();
Start_Load();
}
private static DataTable GetData(string SQLiteCommand)
{
string conString = "Data Source=Books.db;Version=3;";
SQLiteConnection cnn = new SQLiteConnection(conString);
SQLiteCommand command = new SQLiteCommand(SQLiteCommand, cnn);
SQLiteDataAdapter adapter = new SQLiteDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
private void Start_Load()
{
dataGridView1.DataSource = GetData("select * from Books where BookName like '%" + NameTextBox.Text + "%' and AuthorName like '%" + AuthorTextBox.Text + "%' and Genre like '%" + GenreTextBox.Text + "%'");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void SearchButtom_Click(object sender, EventArgs e)
{
Start_Load();
}
private void AddBookButtom_Click(object sender, EventArgs e)
{
AddBookForm AddDialog = new AddBookForm();
AddDialog.Show();
}
private void RefreshButtom_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = GetData("select * from Books");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void InsertFromGridButtom_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string conString = "Data Source=Books.db;Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(conString))
{
using (SQLiteCommand comm = new SQLiteCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
}
}
As you can see i use datagridview datasourse straight from the .db file. And i think, that why i got that error: "DataGridViewCell" does not contain definition for 'Text'"
https://ibb.co/1M4YkZX
How can i fix this?

System.ArgumentException: Data Source cannot be empty

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);
}
}
}

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);
}
}
}

the parameterized query expects the parameter which was not supplied c#

I'm trying to build an application for a fictional music store, but I keep getting this on the #Voornaamklant and #Achternaamklant:
parameterized query expects the parameter which was not supplied
I am retrieving the data from my dataGridView2, which gets its values from another dataGridView and a few TextBoxes. Then what I want to do here is to store everything in dataGridView2 into my database table 'Factuur'.
I have 9 rows in my dataGridView2 and all 9 are coming through in my database correctly. However, I have 10 rows in my table since my first column is an ID Auto_Incremented field, maybe that's something? I dont really think that is causing it though.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NieuwefactuurV2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.dateTimePicker1.Value = DateTime.Now;
}
private void afsluitenToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.SelectedRows[0];
Titel.Text = dr.Cells["titelDataGridViewTextBoxColumn"].Value.ToString();
Prijs.Text = dr.Cells["prijsDataGridViewTextBoxColumn"].Value.ToString();
}
private void Aantal_TextChanged(object sender, EventArgs e)
{
try
{
double a = Convert.ToDouble(Aantal.Text);
double b = Convert.ToDouble(Prijs.Text);
Subtotaal.Text = (a * b).ToString();
}
catch
{
}
}
private void Prijs_TextChanged(object sender, EventArgs e)
{
try
{
double a = Convert.ToDouble(Aantal.Text);
double b = Convert.ToDouble(Prijs.Text);
double c = Convert.ToDouble(Subtotaal.Text);
double d = Convert.ToDouble(Korting.Text);
Subtotaal.Text = (a * b).ToString();
}
catch
{
}
}
private void Subtotaal_TextChanged(object sender, EventArgs e)
{
try
{
double a = Convert.ToDouble(Aantal.Text);
double b = Convert.ToDouble(Prijs.Text);
double c = Convert.ToDouble(Subtotaal.Text);
double d = Convert.ToDouble(Korting.Text);
if (d >= 1 && d < 100)
{
Totaal.Text = (c - (c / 100 * d)).ToString();
}
if (d <= 0)
{
Totaal.Text = (c).ToString();
}
if (d >= 100)
{
Totaal.Text = (0).ToString();
}
}
catch
{
}
}
private void Korting_TextChanged(object sender, EventArgs e)
{
try
{
double a = Convert.ToDouble(Aantal.Text);
double b = Convert.ToDouble(Prijs.Text);
double c = Convert.ToDouble(Subtotaal.Text);
double d = Convert.ToDouble(Korting.Text);
if (d >= 1 && d < 100)
{
Totaal.Text = (c - (c / 100 * d)).ToString();
}
if (d <= 0)
{
Totaal.Text = (c).ToString();
}
if (d >= 100)
{
Totaal.Text = (0).ToString();
}
}
catch
{
}
}
private void Add_Click(object sender, EventArgs e)
{
try
{
string str;
string titel = Titel.Text;
string voorupdate;
str = dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].Cells[4].Value.ToString();
int a = Convert.ToInt32(str);
int b = Convert.ToInt32(Aantal.Text);
voorupdate = (a - b).ToString();
if (a - b >= 0)
{
Print.Enabled = true;
string vnaam = Voornaam.Text;
string anaam = Achternaam.Text;
string lpcd = LPCD.Text;
string dateColumn = dateTimePicker1.Text;
string firstColumn = Titel.Text;
string secondColumn = Aantal.Text;
string thirdColumn = Prijs.Text;
string fourthColumn = Subtotaal.Text;
string fifthColumn = Korting.Text;
string sixthColumn = Totaal.Text;
string[] row = { vnaam, anaam, firstColumn, secondColumn, thirdColumn, fourthColumn, fifthColumn, sixthColumn, lpcd, dateColumn };
dataGridView2.Rows.Add(row);
string cmd = "Update Album set [Actuele Voorraad]='" + voorupdate + "' where Titel='" + Titel.Text + "'";
using (SqlConnection connection = new SqlConnection("Data Source=Evan-PC;Initial Catalog=DatabaseProject;Integrated Security=True"))
{
using (SqlCommand command1 = new SqlCommand(cmd, connection))
{
connection.Open();
command1.ExecuteNonQuery();
}
}
}
else
{
Print.Enabled = false;
MessageBox.Show("Fout");
}
}
catch
{
MessageBox.Show("Vul waarden in");
}
}
private void Remove_Click(object sender, EventArgs e)
{
string str;
string str2;
string titel;
string voorupdate;
titel = dataGridView2.Rows[dataGridView2.SelectedRows[0].Index].Cells[2].Value.ToString();
str2 = dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].Cells[5].Value.ToString();
str = dataGridView2.Rows[dataGridView2.SelectedRows[0].Index].Cells[3].Value.ToString();
int a = Convert.ToInt32(str2);
int b = Convert.ToInt32(str);
voorupdate = ((a + b) - b).ToString();
string cmd = "Update Album set [Actuele Voorraad]='" + voorupdate + "' where Titel='" + titel + "'";
using (SqlConnection connection = new SqlConnection("Data Source=Evan-PC;Initial Catalog=DatabaseProject;Integrated Security=True"))
{
using (SqlCommand command1 = new SqlCommand(cmd, connection))
{
connection.Open();
command1.ExecuteNonQuery();
}
}
if (this.dataGridView2.SelectedRows.Count > 0)
{
dataGridView2.Rows.RemoveAt(this.dataGridView2.SelectedRows[0].Index);
}
else
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseProjectDataSet.Album' table. You can move, or remove it, as needed.
this.albumTableAdapter1.Fill(this.databaseProjectDataSet.Album);
// TODO: This line of code loads data into the 'database_ProjectDataSet2.Album' table. You can move, or remove it, as needed.
this.albumTableAdapter.Fill(this.database_ProjectDataSet2.Album);
}
private void Print_Click(object sender, EventArgs e)
{
try
{
string mail = Email.Text;
string voor = Voornaam.Text;
string achter = Achternaam.Text;
string adres = Adres.Text;
string woon = Woonplaats.Text;
string post = Postcode.Text;
string tele = Telefoonnummer.Text;
try
{
string addcity = "If Not Exists(select * from Woonplaats where Woonplaats='#woon') Begin insert into Woonplaats (Woonplaats)" + "Values('" + woon + "')END";
string dataquery = "INSERT INTO Klant([E-mail], Voornaam, Achternaam, Adres, Woonplaats, Postcode, Telefoonnummer) " +
"Values('" + mail + "', '" + voor + "', '" + achter + "', '" + adres + "', '" + woon + "', '" + post + "', '" + tele + "')";
using (SqlConnection connection = new SqlConnection("Data Source=Evan-PC;Initial Catalog=DatabaseProject;Integrated Security=True"))
{
using (SqlCommand command1 = new SqlCommand(addcity, connection))
using (SqlCommand command = new SqlCommand(dataquery, connection))
{
connection.Open();
command1.Parameters.AddWithValue("#woon", woon);
command1.ExecuteNonQuery();
command.ExecuteNonQuery();
command.Parameters.Clear();
command1.Parameters.Clear();
}
}
}
catch
{
string dataquery = "INSERT INTO Klant([E-mail], Voornaam, Achternaam, Adres, Woonplaats, Postcode, Telefoonnummer) " +
"Values('" + mail + "', '" + voor + "', '" + achter + "', '" + adres + "', '" + woon + "', '" + post + "', '" + tele + "')";
using (SqlConnection connection = new SqlConnection("Data Source=Evan-PC;Initial Catalog=DatabaseProject;Integrated Security=True"))
{
using (SqlCommand command = new SqlCommand(dataquery, connection))
{
connection.Open();
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
}
}
catch
{
MessageBox.Show("Klantgegevens niet goed ingevuld");
}
try
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
string dataquery = "INSERT INTO Factuur VALUES(#Voornaamklant, #Achternaamklant, #Albumtitel, #Aantal, #Prijs, #Subtotaal, #Korting, #Totaal, #CDofLP, #Datuminvoeren)";
using (SqlConnection connection = new SqlConnection("Data Source=Evan-PC;Initial Catalog=DatabaseProject;Integrated Security=True"))
{
using (SqlCommand command2 = new SqlCommand(dataquery, connection))
{
connection.Open();
command2.Parameters.AddWithValue("#Voornaamklant", dataGridView2.Rows[i].Cells["vnaam"].Value);
command2.Parameters.AddWithValue("#Achternaamklant", dataGridView2.Rows[i].Cells["anaam"].Value);
command2.Parameters.AddWithValue("#Albumtitel", dataGridView2.Rows[i].Cells["Albumtitels"].Value);
command2.Parameters.AddWithValue("#Aantal", dataGridView2.Rows[i].Cells["Aantal2"].Value);
command2.Parameters.AddWithValue("#Prijs", dataGridView2.Rows[i].Cells["Prijs2"].Value);
command2.Parameters.AddWithValue("#Subtotaal", dataGridView2.Rows[i].Cells["Subtotaal2"].Value);
command2.Parameters.AddWithValue("#Korting", dataGridView2.Rows[i].Cells["Korting2"].Value);
command2.Parameters.AddWithValue("#Totaal", Convert.ToDecimal((dataGridView2.Rows[i].Cells["Totaal2"].Value)));
command2.Parameters.AddWithValue("#CDofLP", dataGridView2.Rows[i].Cells["CDLP"].Value);
command2.Parameters.AddWithValue("#Datuminvoeren", Convert.ToDateTime(dateTimePicker1.Text));
command2.ExecuteNonQuery();
command2.Parameters.Clear();
}
}
}
}
catch
{
MessageBox.Show("Kan de factuur niet in de database zetten", "Fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
You will get this error if parameter's value is null
So check value before passing it to .Parameters
if(dataGridView2.Rows[i].Cells["vnaam"].Value == null)
command2.Parameters.AddWithValue("#Voornaamklant", DBNull.Value);
else
command2.Parameters.AddWithValue("#Voornaamklant", dataGridView2.Rows[i].Cells["vnaam"].Value);
Your code looks good to me. I would try putting a break point inside the for loop and debugging it. I suspect that you have one more row returning from dataGridView2.Rows.Count than you have data. This would explain why you are seeing the values inserted into Factuur that you want to see, but you are still getting that error message.
I would put a break point at the following lines of code so you can find out what your variable i's value is when you get your exception.
string dataquery = "INSERT INTO Factuur VALUES(#Voornaamklant, #Achternaamklant, #Albumtitel, #Aantal, #Prijs, #Subtotaal, #Korting, #Totaal, #CDofLP, #Datuminvoeren)";
MessageBox.Show("Kan de factuur niet in de database zetten", "Fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
and also at the end of your for loop where you are looping through dataGridView2.Rows.

Categories

Resources