Save location of multiple labels to SQL DB - c#

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

Related

Textbox data is not adding to the database

I'm currently practicing to make a barcode attendance application. After scanning the barcode, the barcode is automatically showing in a text box. There is a add button to send the barcode to the database. But when I click the add button only a blank dataset is adding.(It's working when directly type in the textbox)
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
Here is the add button code
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into student_att (`id`, `nic`, `name`, `address`, `number`, `batch`) select* from student_dt where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
try
{
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1st of all, your queries are quite weird, when you do INSERT, I dont see anywhere what do you actually insert (no data specified in your code), it should be like:
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!=string.Empty)
{
//using means it will close and dispose the classes by it self! So no need to type Close() or Dispose() methods.
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
bool bAllOK = false; //using and helping with some custom flag to get it all right
string query1 = #"INSERT INTO student_att (id, nic, name, address, number, batch) VALUES (#id, #nic, #name, #address, #number, #batch)";
string query2 = #"SELECT * FROM studetnt_att WHERE nibm_id LIKE #myText%";
//1. INSERT:
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.Parameters.AddWithValue("#id", 1); //get new ID, best is to look for the last one in the DB, and increment by 1
cmd.Parameters.AddWithValue("#nic", "nickname1"); //get his nick name
//same way and and set all the other 4 parameters for name, address, number and batch here
try
{
connection.Open();
command.ExecuteNonQuery();
bAllOK = true;
}
catch(SqlException)
{
// error here if occures
}
}
if(bAllOK)
{
//2. SELECT:
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.Parameters.AddWithValue("#myText", textBox1.Text);
DataTable table = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
dataGridView2.DataSource = table;
}
}
}
}
}
else
MessageBox.Show("Please type some name...");
}
The 2nd query makes no sence, since you are looking for nibm_id is looking for IDS which starts with the number in textBox. Is that really what you are looking for? LIKE SOMETHING% means that it looks for SOMETHINGS which starts with that.

How to update a quantity of an item if it already exists in database

I have a productstbl table consisting of Name,Quantity and other attributes.
When I want to buy a new item that is already present in productstbl table I need to update the Quantity.
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Productstbl WHERE Name = #name", con);
con.Open();
cmdCount.Parameters.AddWithValue("#name", NameBox.Text);
int count = (int)cmdCount.ExecuteScalar();
con.Close();
if (count > 0)
{
SqlCommand cmd = new SqlCommand("SELECT Qunatity FROM Productstbl WHERE Name = #name, Quantity = #quantity", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
int ExistingQTY = (int)cmdCount.ExecuteScalar(); // I get error here
}
cmd = new SqlCommand("INSERT INTO Historytbl (Name, Date, Price, Quantity, Total_Price, Sup_Name, Process, Retail_Price) VALUES (#name, #date, #price, #quantity, #total_price, #sup_name, #process, #retail_price)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#price", PriceBox.Text);
cmd.Parameters.AddWithValue("#quantity", ExistingQTY);
cmd.Parameters.AddWithValue("#total_price", TotalPriceBox.Text);
cmd.Parameters.AddWithValue("#sup_name", comboBox1.Text);
cmd.Parameters.AddWithValue("#process", "buy");
cmd.Parameters.AddWithValue("#retail_price", RetailPriceBox.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
DisplayData();
ClearData();
If you want to update a quantity of a product, it is best for to get the quantity in the database if it already exists the database.
I make a code example, you can have a look.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Juice");
comboBox1.Items.Add("Apple");
comboBox1.Items.Add("Milk");
ShowData();
}
public void ShowData()
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string cmd = "select * from Product";
DataSet set = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd, connection);
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Product WHERE Name = #Name", connection);
cmdCount.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if(count>0)
{
SqlCommand command = new SqlCommand("SELECT Quantity FROM Product WHERE Name = #Name",connection);
command.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["Quantity"]);
}
}
SqlCommand updatecmd = new SqlCommand("Update Product set Quantity=#Quantity, Date=#Date where Name=#Name",connection);
updatecmd.Parameters.AddWithValue("#Quantity", i + numericUpDown1.Value);
updatecmd.Parameters.AddWithValue("#Date", DateTime.Now);
updatecmd.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Update successfully");
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Product(Name,Quantity,Date,Price)values(#Name,#Quantity,#Date,#Price)",connection);
insertcmd.Parameters.AddWithValue("Name", comboBox1.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#Quantity",numericUpDown1.Value);
insertcmd.Parameters.AddWithValue("#Date",DateTime.Now);
insertcmd.Parameters.AddWithValue("Price",Convert.ToInt32(textBox1.Text));
insertcmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Insert successfully");
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString()== "Juice")
{
textBox1.Text = "10";
}
if (comboBox1.SelectedItem.ToString() == "Apple")
{
textBox1.Text = "5";
}
if (comboBox1.SelectedItem.ToString() == "Milk")
{
textBox1.Text = "8";
}
}
Tested Result:

How to get an integer value from SQL database to a variable in windows forms (C#)?

I've created a form called BookSeat which takes no.of seats as an input and calculate the total fare.
Here's my code:
{
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This shows and error : Invalid attempt to read when no data is present
SqlDataReader has the method called Read which reads all the data inside sqldatareader. But you have to call this function inside while loop.
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
While(dr.Read())
{
//Get value by using column name;
int d = Convert.ToInt32(dr["columnname"]);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
}
dr.Close();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

InvalidOperationException exception while trying to execute an update query

private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.
da.UpdateCommand.ExecuteNonQuery() is not getting executed
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
Don't use adapter.
And yes. Faster of all try to close connection and open new one for update operation.

Why my dropdown list don't fill up textboxes?

I have a dropdownlist item named IsAuthor. It do not fill my textboxes by retrieving value from tblnewgroup table. Where is the problem I can not understand and it do not show any error please help me
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno='" + lstAuthor.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
I filled my drop down list by these codes..
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT Groupname, Groupno FROM tblnewgroup";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Groupname"].ToString();
newItem.Value = reader["Groupno"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
Problem : you are assigning single quotes to number feild Groupno.
Solution : you need to assign single quotes to VARCHAR Types only.
Suggestion: you are just assigning the values from SqlDataReader object without checking for rows.if the rows are not found then it will throw the Exeption. So i would suggest to Ceck the SqlDataReader object for any rows before assigning the values to TextBox Controls.
Try This:
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedValue;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
lblResults.Text = "Data Updated Successfully!";
}
else
{
lblResults.Text = "No Records found!";
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
It looks like you're selecting on a number field, but treating it like a text field. Modify your query to remove the single quotes:
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedItem.Value;
Also check the return value of reader.read() to see if there are any records:
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
else
{
lblResults.Text = "Author not found";
}
}
Note that I've put the reader in a using block to ensure it is closed, even if an exception occurs.
I assume SqlDataReader.Read method returns boolean value and you can use it like;
while(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
Also I suspect lstAuthor.SelectedItem.Value is a number instead of a string. You might need to use it without using "".
Also using parameterized queries always a good choice.
selectSQL = "SELECT * FROM tblnewgroup WHERE Groupno = #Groupno";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#Groupno", lstAuthor.SelectedItem.Value);
....
Use following:
while (reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}

Categories