Update query not working in C# - c#

protected void btn_redeem_Click(object sender, EventArgs e)
{
int lol = int.Parse(lbl_TotalPrice.Text,System.Globalization.NumberStyles.Currency);
double nprice = lol * 0.05;
int newpoints=0 ;
if (int.Parse(Session["points"].ToString()) >= 1000)
{
double redeem = lol - nprice;
lbl_TotalPrice.Text = redeem.ToString("C");
newpoints = int.Parse(Session["points"].ToString()) - 1000;
}
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string queryStr = "UPDATE Users SET Points ='" + newpoints + "'WHERE UserName=" + Session["New"].ToString();
SqlCommand com = new SqlCommand(queryStr, conn);
conn.Close();
}

Add .ExecuteNonQuery to execute the query, and add try-catch-block to catch any exception:
try
{
...
SqlCommand com = new SqlCommand(queryStr, conn);
com.ExecuteNonQuery();
conn.Close();
...
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

Related

How can i use HiddenField id as a variable for its value in c#

I have 1000 hiddenfield. How can i put their value in sql database using for loop. Like:
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
string sqlquery = ("INSERT INTO [" + table_name2 + "] (CT1) VALUES ('" + p + "')");
SqlCommand command = new SqlCommand(sqlquery, Connection);
command.ExecuteNonQuery();
}
change tablename as requred!
string query = "INSERT INTO tablename ( CT1 ) VALUES ( #value )";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con);
try
{
cmd.Parameters.Add("#value", System.Data.SqlDbType.VarChar);
con.Open();
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
cmd.Parameters["#value"].Value = p;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//Show exception as required!
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}

Getting database ID from combobox

I have got a problem.
I need to get id_subcategoria in 2 combobox "1". I have this code:
void fill_cbsubcategoria(int masterId)
{
cbsubcategoria.Items.Clear();
cbproduto.Items.Clear();
cbproduto.Text = "Escolha o produto";
txtquantidade.Text = null;
txtpreco.Text = null;
txtiva.Text = null;
try
{
con.Open();
string Query = "select * from Subcategoria where id_categoria = #mid";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.Parameters.AddWithValue("#mid", masterId);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
int id_subcategoria = (int)dr.GetInt32(0);
string subcategoria = (string)dr.GetString(1);
cbsubcategoria.Items.Add(id_subcategoria.ToString() + " - " + new SubCategoriaHolder(id_subcategoria, subcategoria));
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
And I need to have id_subcategoria, when clicking at "Guardar".
private void btnguardar_Click(object sender, EventArgs e)
{
try
{
con.Open();
string Query = "insert into dbPAP.Produtos (id_subcategoria, nome_produto, quantidade, preco_unitario, iva, imagem)" + "values('" + "I NEED THAT ID FROM COMBOBOX" + this.txt_nproduto.Text + this.txtquantidade.Text + this.txtpreco.Text + this.txtiva.Text + "') ;";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
MessageBox.Show("Adicionado com sucesso!");
while (dr.Read())
{
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here's my button guardar code.
Note: I don't want SelectedValue from combobox, I want to get id_subcategoria from DataBase.
Just add the ID's to a array List, while loading the elements to the combo Box, the Selected index from the combo box should reference to the according id in the List

Adding data in sql Table columns

I have this basic WinForms application user interface:
And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName ProduktTable ("
+ dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
+ dataGridView1.Rows[i].Cells["Antal"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:
What's wrong with the procedure ?.
Thanks in advance
The format for an insert name doesn't require the words tableName. It wants the actual table name.
INSERT INTO tableName ProduktTable
should be
INSERT INTO ProduktTable
assuming Produ**K**tTable isn't a typo.

Save location of multiple labels to SQL DB

Hello this is code which creates multiple labels to exact position that is saved in SQL DB. Now I'm wondering how it will be possible to save location of each label (because I'm able to move them like Drag and drop). I was wondering how should the code look like because when I create a label during runtime it is without name, isn't it? I'm not sure how it should be assigned.
Would anyone help me solve this out please?
This is the code for load:
private void createLabelFromSql()
{
try
{
string query = "SELECT * FROM [schema] WHERE id=#id";
SqlCommand com = new SqlCommand(query, conn);
com.Parameters.AddWithValue("#id", idSch);
conn.Open();
SqlDataReader read= com.ExecuteReader();
while (read.Read())
{
mouseX = Int32.read(read["x"].ToString());
mouseY = Int32.read(read["y"].ToString());
createLabelCmd();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
finally { conn.Close(); }
}
private void createLabelCmd()
{
newLabel = new Label();
newLabel.Location = new Point(mouseY, mouseX);
newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
panel1.Controls.Add(newLabel);
}
I thought that it might be somehow like this but not sure how to handle the name thing:
string query = "UPDATE [schema] SET x=#x, y=#y WHERE id=#id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#x",label1.Location.X);
cmd.Parameters.AddWithValue("#y", label1.Location.Y);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Thank you for your time.
My way:
private void createLabelFromSql()
{
try
{
string query = "SELECT * FROM [schema] WHERE id=#id";
SqlCommand com = new SqlCommand(query, spojeni);
com.Parameters.AddWithValue("#id", idSch);
spojeni.Open();
SqlDataReader precti = com.ExecuteReader();
while (precti.Read())
{
createLabelCmd((int)precti["x"], (int)precti["y"]);
}
spojeni.Close();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
finally { spojeni.Close(); }
}
private void createLabelCmd(int x, int y)
{
var newLabel = new Label();
newLabel.Location = new Point(y, x);
newLabel.Font = new Font(newLabel.Font.FontFamily.Name, 9, FontStyle.Bold);
newLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
panel1.Controls.Add(newLabel);
}
private void SaveAllLabels()
{
spojeni.Open();
//delete all data
SqlCommand delCmd = new SqlCommand("DELETE FROM [schema] WHERE id=#id", spojeni);
delCmd.Parameters.AddWithValue("#id", idSch);
delCmd.ExecuteNonQuery();
//create new data for current state
string query = "INSERT INTO [schema] VALUES (#x, #y, #id)";
SqlCommand cmd = new SqlCommand(query, spojeni);
cmd.Parameters.Add("#x", SqlDbType.Int);
cmd.Parameters.Add("#y", SqlDbType.Int);
cmd.Parameters.AddWithValue("#id", idSch);
foreach (Control item in panel1.Controls)
{
if (item is Label)
{
cmd.Parameters["#x"].Value = item.Location.X;
cmd.Parameters["#y"].Value = item.Location.Y;
cmd.ExecuteNonQuery();
}
}
spojeni.Close();
}
Why don't you give each label a name?
Eidt:
Assuming id is the Primary Key of the table you can get it via:
private void createLabelFromSql()
{
....
....
while (read.Read())
{
mouseX = Int32.read(read["x"].ToString());
mouseY = Int32.read(read["y"].ToString());
createLabelCmd(Int32.Parse(read["id"].ToString())); // you can extract the id here
}
conn.Close();
}
And alter saving method as:
string query = "UPDATE [schema] SET x=#x, y=#y WHERE id=#id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#x",label1.Location.X);
cmd.Parameters.AddWithValue("#y", label1.Location.Y);
cmd.Parameters.AddWithValue("#id", int.Parse(label1.Name.Replace("lbl","")));
....
End of Edit ,
private void createLabelCmd(int id)
{
newLabel = new Label();
newLabel.Name = "lbl" + id.ToString();
newLabel.Location = new Point(mouseY, mouseX);
.....
.....
}

fatal error encountered during command execution c# mysql

private void button1_Click_1(object sender, EventArgs e)
{
try
{
string myConnection = " datasource=**.**.**.**;port=3306;username=****;password=****;";
MySqlConnection myconn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from forma.user where username='" + this.username_txt.Text + "' and password= '" + this.password_txt.Text + "' ; ", myconn);
MySqlDataReader myreader;
myconn.Open();
myreader = SelectCommand.ExecuteReader();
int count = 0;
while (myreader.Read())
{
count = count + 1;
}
if (count == 1)
{
// MessageBox.Show("Prijava uspešna");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Podobojeno uporabniško ime");
}
else
{
MessageBox.Show("uporabniško ime ali geslo ni pravilno.");
myconn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a problem connecting to remote server, it gives me error (title). Can you please tell me what I did wrong and how can I fix it? Thanks.
give the connection string as below
string myConnection = "Server=**.**.**.**;Port=3306;Database=***;Uid=***;Pwd=***;"
Use SQL parameters, your application is widely open for sql injection attacks

Categories