I am currently using a databound CheckBoxList and I need to identify the status of what checkbox was checked, and unchecked, etc. Basically when a user presses a checkbox it autopostbacks, I read some data from the database, and have a running Session with totals. What I need is when a checkbox is unchecked to identify this change, also make a database call, and substract the amount that product is supposed to cost. Or maybe just read every checkbox everytime a checkbox is checked/unchecked but I'd think that's less optimal.
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Name", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Price = 0;
while (reader.Read())
{
Price = Convert.ToDecimal(reader["Price"]);
}
Total = Convert.ToDecimal(Session["Total"]);
Total = Total + Price;
Session["Total"] = Total;
}
I just need to identify what checkbox was unchecked and run a similar query to substract from the total. THanks for any help :)
EDIT: Updated code (made some adjustments to variables and stuff as well):
if (Session["previouslySelected"] != null && Session["previouslySelected"].ToString() != "-1")
{
decimal CompraTotal2 = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal2 = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal2 = Precio - CompraTotal2;
Session["CompraTotal"] = CompraTotal2;
}
if (CheckBoxList1.SelectedIndex != -1)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
int i = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal = CompraTotal + Precio;
Session["CompraTotal"] = CompraTotal;
}
Session["previouslySelected"] = CheckBoxList1.SelectedIndex;
Label3.Text = Convert.ToString(Session["CompraTotal"]);
}
The problem I am facing know is that the first part of the code also executes at the same time as the other one, giving me bad values. I have two items databound to my CheckList, I have Option 1 and Option 2. I concatenated the values for the text since there are prices, so what I am displaying is Option 1 $1.00 Option 2 $0.50. With the query I get a specific GUID and since the name is unique I look up the Price value. If the checkbox was unchecked it should check for that value, then subtract from the current total. If the checkbox was checked it should then look for that value and add it.
FINAL FIXED CODE FOR THOSE WHO ARE IN THE SAME SITUATION
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
values += CheckBoxList1.Items[i].Value + ",";
\\COMMANDS EXECUTE HERE
}
}
if (Session["previouslySelected"] != null && Session["previouslySelected"].ToString() != "-1")
{
decimal CompraTotal2 = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", Session["previouslySelected"].ToString());
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal2 = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal2 = Precio - CompraTotal2;
Session["CompraTotal"] = CompraTotal2;
}
if (CheckBoxList1.SelectedIndex != -1)
{
decimal CompraTotal = 0;
MySqlConnection connection = new MySqlConnection(GlobalVars.mysql);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "QUERY";
command.Parameters.AddWithValue("?GUID", Session["GUID"]);
command.Parameters.AddWithValue("?Nombre", CheckBoxList1.SelectedValue);
MySqlDataReader reader = command.ExecuteReader();
decimal Precio = 0;
int i = 0;
while (reader.Read())
{
// reader.GetString(0);
Precio = Convert.ToDecimal(reader["Precio"]);
}
CompraTotal = Convert.ToDecimal(Session["CompraTotal"]);
CompraTotal = CompraTotal + Precio;
Session["CompraTotal"] = CompraTotal;
}
Session["previouslySelected"] = CheckBoxList1.SelectedIndex;
Label3.Text = Convert.ToString(Session["CompraTotal"]);
}
Related
Have the error 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException, however VisualStudio does not pause the program and throw the exception at me. Here is the code:private void BTN_NA_Click(object sender, EventArgs e)
{
if (TXT_NAUN.Text != "" && TXT_NAPW.Text != "" && TXT_NAPW2.Text != "")
{
if (TXT_NAPW.Text == TXT_NAPW2.Text)
{
string input = TXT_NAPW.Text;
int hash = 0;
int output = 0;
foreach (char chara in input)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
output = output + temp;
output = output * 2;
}
hash = output % 1000;
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT Accounts.PlayerID FROM Accounts ORDER BY Accounts.PlayerID DESC ";
///string comm = "SELECT Accounts.PlayerID from Accounts";
/// INNER JOIN Leaderboard ON Leaderboard.PlayerID = Accounts.PlayerID WHERE Accounts.PlayerUsername = #ip";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
string result = "";
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
dbConn.Close();
{
string comm = "INSERT INTO Accounts (PlayerUsername, PlayerPassword, PlayerID, PlayerInvID) VALUES (#NAUN, #HPW, #NAPI, #NAPI)";
OleDbCommand command = new OleDbCommand(comm, dbConn);
command.Parameters.AddWithValue("#NAUN", TXT_NAUN.Text);
command.Parameters.AddWithValue("#HPW", hash);
foreach (char chara in result)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
result = result + temp;
}
result = result + 1;
command.Parameters.AddWithValue("#NAPI", result);
command.Parameters.AddWithValue("#NAPI", result);
dbConn.Open();
int rowsAffected = cmd.ExecuteNonQuery(); ///error appears here
dbConn.Close();
}
}
}
}
Any suggestions on solution, have tried a lot and this is my last hope!
Thanks,
Blackclaw_
At the line you got the error, you are using cmd (the select command). I think you want to use command (the insert command).
I have a table which has 3 columns and each column has 5 rows.Now I wanna get those total numbers of rows in c# to create that number of labels dynamically as well as get the rows value for labels name.Similarly, creates same numbers of the textbox as well.Then in the runtime, i wanted to submit the value to the database by this textbox.
Note: here, if I increase the rows of the table,then the label and textbox will be increased automatically/dynamically as well as submitting value through textbox will perfectly work.
But , all I have done is only getting count value 1 , I just tried a lot but not getting the total count value which is actually 5 .
here, is my code...
private void Form1_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
int count = rdr.FieldCount;
while (rdr.Read())
{
//System.Windows.Forms.Label MyLabel;
{
int y = 50;
Label myLabel = new Label();
for (int i = 0; i < count; i++)
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[i].ToString();
y += 25;
this.Controls.Add(myLabel);
}
}
}
}
}
}
And I got this output.
The issue seems that you are using query as count but you want the values of the field. So you can probably change it to
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
Int32 count = (Int32) cmd.ExecuteScalar();
int i = 1;
cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
SqlCommand cmd1 = new SqlCommand(cmText, con);
using (SqlDataReader rdr = cmd1.ExecuteReader())
{
int y = 50;
Label myLabel = new Label();
TextBox MyTxt = New TextBox();
while (rdr.Read())
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[1].ToString(); //Since you want ProductName here
y += 25;
this.Controls.Add(myLabel);
//Same Way Just include the TextBox
//After all Position of TextBox
MyTxt.Text = rdr[2].ToString(); // I believe you need UnitPrice of the ProductName
i++;
}
}
}
Count(columname) :
Will count only the NOT NULL values in that column.
Count(*) :
Will count the number of records in that table.
So I guess you have some NULL values in ProductId column. Change it to
Select Count(*) from tblProductInventory
I've got a DataGridView that has 2 columns - product name and the quantity of it. So I grab each row in a foreach loop and calculate the price of it. I managed to do that but I can't seems to figure out how to store ALL the calculated rows into a single variable and insert them into a database.
This is what I have so far:
string cMedication = string.Empty;
string cQuantity = string.Empty;
string cAppointment = string.Empty;
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
cMedication = row.Cells[0].Value.ToString();
cQuantity = row.Cells[1].Value.ToString();
cAppointment = txtAppointmentID.Text;
if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
{
MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
}
else
{
//this.savePrescription(cMedication, cQuantity, cAppointment);
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
string strCalc = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= ('" + cMedication + "')";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdCalc = new SqlCommand(strCalc, connection))
{
connection.Open();
SqlDataReader readPrice = cmdCalc.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
double result = doublePrice * doubleQuantity;
string answer = result.ToString();
//insert TOTAL amount to database below
}
readPrice.Close();
connection.Close();
}
}
}
}
If you're doing this kind of thing a lot then I would use some kind of ORM like Entity Framework (or write your own). Then you would just load / create entites and save them.
If that's overkill for what you're doing then you could build up an insert statement and execute it, much like you've done to query the medication price. Only as I've mentioned in the comment, use SqlParameters instead of string concatenation to avoid possible sql injection attacks.
Something like this (untested).
var builder = new StringBuilder("INSERT INTO MedicationLine (MedicationName, Quantity, Price) VALUES ");
int i = 0;
var parameters = new List<SqlParameter>();
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
string cAppointment = txtAppointmentID.Text;
if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
{
MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
return;
}
string cMedication = row.Cells[0].Value.ToString();
string cQuantity = row.Cells[1].Value.ToString();
i++;
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
string strCalc = "SELECT medicationPrice FROM MEDICATION WHERE medicationName = #medicationName";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdCalc = new SqlCommand(strCalc, connection))
{
command.Parameters.Add(new SqlParameter("medicationName", cMedication);
connection.Open();
SqlDataReader readPrice = cmdCalc.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
builder.AppendLine();
builder.Append("(";
builder.Append("#Name");
builder.Append(i);
builder.Append("#Qty");
builder.Append(i);
builder.Append("#Price");
builder.Append(i);
builder.Append("),";
parameters.Add(new SqlParameter("Name" + i.ToString(), medicationName);
parameters.Add(new SqlParameter("Qty" + i.ToString(), doubleQuantity);
parameters.Add(new SqlParameter("Price" + i.ToString(), doublePrice);
}
readPrice.Close();
connection.Close();
}
}
}
The idea is to end up with something like:
INSERT INTO MedicationLine (MedicationName, Quantity, Price) VALUES
(#Name1, #Qty1, #Price1),
(#Name2, #Qty2, #Price2),
(#Name3, #Qty3, #Price3),
...
Then execute it. Don't forget to trim the trailing comma.
using (var connection = new SqlConnection(strConnectionString))
{
using (var command = new SqlCommand(builder.ToString().TrimEnd(','), connection))
{
command.Parameters.AddRange(parameters.ToArray());
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
}
**Disclaimer
Syntax may be wrong as done without an IDE!
I'm getting the error:
Invalid attempt to access a field before calling Read()
at: string result = Reader.GetString(0);
I'm not entirely sure what to do or whats wrong though
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
// Initialize MySQL Reader
Reader = command.ExecuteReader();
Reader.Read();
string result = Reader.GetString(0);
// If the character doesn't exist or isn't entered, return 0
int charguid = 0;
if (result != String.Empty)
{
charguid = Convert.ToInt32(result);
}
return charguid;
}
Change the code to:
Reader = command.ExecuteReader();
int charguid = 0;
if(Reader.Read())
{
if(Reader[0] != DBNull.Value)
{
if(int.TryParse(Reader[0].ToString(), out charguid))
{
//value read and is an integer!
}
}
}
return charguid;
You should use ExecuteScalar instead of ExecuteReader
ExecuteSaclar returns the first column of the first row in the result
set, or a null reference
ExecuteReader will return as resultset which you have to then iterate
to read
So looking at your code you just want the first column of the result set
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
int charguid = 0;
using(MySqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
object obj = command.ExecuteScalar();
if (obj != null && obj != DBNull.Value)
{
charguid = Convert.ToInt32(obj);
}
}
return charguid;
}
openConnection()
sql = "SELECT last, first, emp_type, active FROM employee INNER JOIN account ON employee.emp_id = account.emp_id WHERE employee.emp_id = '" & AtxtEmpID.Text & "'"
command = New MySqlCommand(sql, mySqlConnection)
reader = command.ExecuteReader
reader.Read()
AtxtEmpName.Text = reader.Item(0) & ", " & reader.Item(1)
closeConn()
have the save problem
I was trying to remove duplicates from the table Main.
It looks like this(here in csv form):
"Record ID";Status;Placement;Private;Category;Note;Blob
for instance
14341692;132;2147483647;False;4;"29.12.10 14:17";System.Byte[]
Duplicates means, Note is the same. My approach is this:
string strSQL = "SELECT * FROM Main";
OleDbCommand cmd = new OleDbCommand(strSQL, MemoVerbindung);
OleDbDataReader dr = cmd.ExecuteReader();
_items = new List<string>(); // <-- Add this
while (dr.Read())
{
if (dr.FieldCount >= 5)
_items.Add(dr[5].ToString());
}
dr.Close();
progressBar1.Maximum = _items.Count;
for (int a = 0; a < _items.Count; a++)
{
progressBar1.Value = a;
strSQL = "SELECT * FROM Main WHERE Note = '" + _items[a].ToString().Replace("'", "\'") + "'";
cmd = new OleDbCommand(strSQL, MemoVerbindung);
dr = null;
OleDbDataReader dr2 = null;
try
{
dr = cmd.ExecuteReader();
int u = 0;
if (dr.FieldCount > 1)
{
while (dr.Read())
{
if (u >= 1)
{
string was = "DELETE FROM Main WHERE [Record ID] = " + dr[0];
OleDbCommand command = new OleDbCommand(was, MemoVerbindung);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader[0].ToString());
}
reader.Close();
}
u++;
}
}
else
{
while (dr.Read())
{
MessageBox.Show("Übrig");
}
}
dr.Close();
}
catch (Exception mm)
{
//MessageBox.Show(mm.Message);
}
}
MessageBox.Show("Fertig");
progressBar1.Value = 0;
So in the if (u >= 1) section I am trying to leave one version while removing all others. Unfortunately that does not work meaning all entries are removed but the ones raising an error for a reason. What would you change or is there a generally more elegant way?
Use this SQL statement to find the duplicates:
SELECT First(Main.[Note]) AS [NoteField], Count(Main.[Note]) AS NumberOfDups
FROM Main
GROUP BY Main.[Note]
HAVING (((Count(Main.[Note]))>1));
then you can loop through this recordset (grab it as a SnapShot so changes to the underlying data does not change the results)
use !NoteField to know which note to find, and !NumberOfDups to know how many you have to delete (remove this number - 1)