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.
Related
after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}
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)
{
}
I am trying to create a chart that when, at the push of a button displays a chart that shows the user the number of times a record has appeared in the dataset/table that it is linked to. Please bare in mind that I have little experience with using Charts in Visual Studios/C#.
Currently I am getting this error: Error
This is all the code I have so far:
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 System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Select = "SELECT * FROM tblReject_test";
string DataConnection;
string Department = txtDepartment.Text;
string Start_Date = txtStart.Text;
string End_Date = txtEnd.Text;
string Anatomy = txtAnatomy.Text;
string RFR = cmbRFR.Text;
string Comment = txtComment.Text;
//Select defines what should be loaded on to the dataset.
if (Department != "")
{
Select = Select + " WHERE department_id =" + "'" + Department + "'";
if (Anatomy != "")
{
Select = Select + "AND body_part_examined =" + "'" + Anatomy + "'";
if (Start_Date != "")
{
Select = Select + " AND study_date =" + "'" + Start_Date + "'";
if (End_Date != "")
{
Select = Select + " AND study_date =" + "'" + End_Date + "'";
if (RFR != "")
{
Select = Select + " AND reject_category =" + "'" + RFR + "'";
if(Comment != "")
{
Select = Select + " AND reject_comment =" + "'" + Comment + "'";
}
}
}
}
}
}
else
{
Select = "SELECT * FROM tblReject_test";
}
//DataConnection connects to the database.
string connectiontring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
private void btnLoadChart_Click(object sender, EventArgs e)
{
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
Your code wouldn't compile as you are assigning a string to DataConnection (instance of OleDbConnection).
The correct usage should be as following.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring));
Also, your code doesn't close Database connection in case of exception.
It would be recommended to use the code as shown below. This is taken from MSDN
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("DataSource: {0} \nDatabase: {1}",
connection.DataSource, connection.Database);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
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))
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