C# Message box multiple display in a row - c#

I'm doing this code for list view to database i wanted to save all the columns, it saves but it display a messagebox in each row. Can somebody help me out to fix this i want to display only one messagebox when the button's click.
So here is my code
foreach (ListViewItem li in listView1.Items)
{
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into cashier.sales(Cashier,Orders,Quantity,Size,Price,Date) values ('" + this.cashier.Text + "','" + li.SubItems[0].Text + "','" + li.SubItems[1].Text + "','" + li.SubItems[2].Text + "','" + li.SubItems[3].Text + "','" + this.dateTimePicker1.Value + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(cashier.Text))
{
MessageBox.Show("Please fill the Notes. ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Order has been added successfully ", "Order!", MessageBoxButtons.OK, MessageBoxIcon.Information);
total.Text = "";
amount.Text = "";
change.Text = "";
while (myReader.Read())
{
}
}
}

Move the MessageBoxoutside of your loop
foreach (ListViewItem li in listView1.Items)
{
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into cashier.sales(Cashier,Orders,Quantity,Size,Price,Date) values ('" + this.cashier.Text + "','" + li.SubItems[0].Text + "','" + li.SubItems[1].Text + "','" + li.SubItems[2].Text + "','" + li.SubItems[3].Text + "','" + this.dateTimePicker1.Value + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(cashier.Text))
{
MessageBox.Show("Please fill the Notes. ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
total.Text = "";
amount.Text = "";
change.Text = "";
while (myReader.Read())
{
}
}
}
MessageBox.Show("Orders has been added successfully ", "Order!", MessageBoxButtons.OK, MessageBoxIcon.Information);

Related

How do you insert multiple rows to datagridview on C#?

private void btn_insert_item_Click(object sender, EventArgs e)
{
if(textBox9.Text != "" & textBox10.Text != "" & textBox11.Text != "")
{
DialogResult dialog = MessageBox.Show("Do you want to add item #" + textBox11.Text + "?",
"", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
try
{
con.Open();
OracleCommand cmd = new OracleCommand("insert " +
"into table_a " +
"(order_date, " +
"order_no, " +
"item_name, " +
"item_no) " +
"values( " +
"sysdate, " +
"'" + textBox9.Text + "', " +
"'" + textBox10.Text + "', " +
"'" + textBox11.Text + "', " +
)", con);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt;
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
MessageBox.Show("item has been added.");
}
}
if (dialog == DialogResult.No)
{
MessageBox.Show("No change has been made.");
button1_Click(sender, e);
}
}
}
This is code I use to insert single item # on table_a.
textBox 9 = order_date, textBox10 = order_no and textBox11 = item_no.
if I have textBox12 for item_no too then how do I insert multiple row with item_no on dataGridView? If I put item_no 1 on textBox11 and 10 on textBox12, it should insert 10 rows with same information but item_no from 1 to 10.
Help Please.
Try to create a loop with textBox12.text as the counter
For example:
for(int x=1;x<textBox12.text;x++)
{
//Your code.....
}

connection string is not correct, how to fix it?

I'm using visual studio 2017 community and i'm trying to create local data base and I have a problem in the connection string since it dont connect when run it step by step its stuck in conn.Open();
this is the code of the connection and the executenonquery:
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
image screenshot of visual:
image screenshot
The entire code:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(??,???,?????,???? ?????,????,???? ?????,????,???,??)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
}
}
Use the connection string available in properties tab of the screenshot you have attached if the problem is of connection string
This is what I'm talking about
Use this as connection string, also remember to replace password value from '*' to actual value.

Error connecting to Local Data Base i need to pass info from CSV file into the localdb table c#

I have an error message when I'm trying to run the code and pass the information from a CSV file into the Local DataBase
the error message is :
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
and I'm not sure what is the problem in here:
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','"
+ rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6]
+ "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
image screenshot of visual:
image screenshot
when I run the app the LOCALDBSHILOV have a red X on him is it noraml
red X image
the code is:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('"
+ rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','"
+ rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
Your connection string is not correct. Use one like this:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
when i run it its stuck in conn.Open(); and does nothing and there is no error but the application continues to run only that it does not pass to the next line of code and there is no update of the table
try
{
//SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}

How to save value for foreign keys?

I want save the ID of the selected subjectname in a DataGridView and also the ID of the student whose year level is selected in the combobox. So my reference for getting the student and subject is the school year and the year level. I want to save it in my table Schedule which has Registration_registrationID (FK), Student_studentID (FK), yearlevel and schoolyear:
Here's my code :
private void btn_add_Click(object sender, EventArgs e)
{
string reg = "";
string schoolyear = txt_startYr.Text + "-" + txt_endYr.Text;
MySqlConnection conn, conn1, conn2;
MySqlCommand cmd2;
MySqlDataReader reader, reader1;
List<DataGridViewRow> selectedRows = (from row in dg_subjects.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells[3].Value) == true select row).ToList();
if (selectedRows.Count >= 1)
{
if (MessageBox.Show(string.Format("Are you sure you want to add this subject?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow row in selectedRows)
{
try
{
conn = new MySqlConnection(myconn);
conn.Open();
string subject = "Select subjectID from southpoint_school.subject WHERE subject_name = '" + row.Cells[0].Value.ToString() + "';";
MySqlCommand cmd = new MySqlCommand(subject, conn);
reader = cmd.ExecuteReader();
reader.Read();
string subj = reader.GetString("subjectID");
conn.Close();
conn1 = new MySqlConnection(myconn);
conn1.Open();
string query = "Select regID from southpoint_school.registration where yearLevel = '" + cmb_year.Text + "' AND schoolYear = '" + schoolyear + "';";
MySqlCommand cmd1 = new MySqlCommand(query, conn1);
reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
conn2 = new MySqlConnection(myconn);
reg = reader1.GetString("regID");
string query1 = "INSERT INTO southpoint_school.schedule (Registration_regID, Subject_subjectID, yearLevel, school_year) values ('" + reg + "','" + subj + "','" + cmb_year.Text + "','" + schoolyear + "')";
cmd2 = new MySqlCommand(query1, conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
MessageBox.Show("Successfully Saved");
conn2.Close();
}
conn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
else
{
MessageBox.Show("Please select a Subject");
}
}
It doesn't give an error but it does nothing.

i m getting error in the following cede. (System.Data.OleDb.OleDbException: ORA-00933: SQL command not properly ended)

protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.

Categories