I want to draw a stacked chart from mysql database.
I want to have 4 columns named "port1", "port2", "port3" and "port4".
My problem is when I import the data from my DB, I check the type a column in the table then I draw the chart . My DB contains 4 types of port consequently I would have 4 columns named port1, port2, port3 and port4, but my code generate all the data but on the same column which is port1.
How can I add an identical number of datapoints?
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
string query4 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port4'";
SqlCommand cmmd = new SqlCommand(query1, con);
SqlCommand cmmd4 = new SqlCommand(query4, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
SqlCommand cmmd = new SqlCommand(query1, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query2 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port2'";
SqlCommand cmmd2 = new SqlCommand(query2, con);
SqlDataReader dataReader2 = cmmd2.ExecuteReader();
while (dataReader2.Read())
{
chart1.Series.Add(dataReader2["name"].ToString());
chart1.Series[dataReader2["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader2["name"].ToString()]["StackedGroupName"] = "Group2";
// MessageBox.Show(dataReader2["type"].ToString());
chart1.DataBind();
chart1.Series[dataReader2["name"].ToString()].Points.AddXY("Port_2", dataReader2["value"].ToString());
chart1.Series[dataReader2["name"].ToString()]["PointWidth"] = "1";
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error "+ ex);
}
Related
https://ibb.co/DkKdpnL
This is the code im using in the Database controller. Im sure there is nothing wrong with this code but i keep on getting the error message when I select a date from the Monthly calender Picker.
{
SqlDataReader reader;
SqlCommand command;
Collection<StockItem> items;
try
{
DateTime input;
DateTime.TryParse(date, out input);
command = new SqlCommand("SELECT * FROM StockItem WHERE DATEDIFF(day, stockItemExpiryDate,'" + input.ToString() + "') >= 0 ORDER BY stockItemShelfNumber", cnMain);
cnMain.Open();
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
items = new Collection<StockItem>();
if (reader.HasRows)
{
while (reader.Read())
{
StockItem item = new StockItem();
item.expiryDate = reader.GetDateTime(1).ToShortDateString();
item.shelfNumber = reader.GetString(2);
item.numberInStock = reader.GetInt32(3) + "";
item.productRef = reader.GetInt32(4) + "";
SqlConnection connection = newConn();
SqlCommand command2 = new SqlCommand("SELECT productPackaging FROM Product WHERE productID =" + item.productRef + ";", connection);
connection.Open();
command2.CommandType = CommandType.Text;
SqlDataReader reader2 = command2.ExecuteReader();
String description = "";
if (reader2.HasRows)
{
reader2.Read();
description = reader2.GetString(0);
}
reader2.Close();
connection.Close();
item.productRef = description;
items.Add(item);
}
}
reader.Close();
cnMain.Close();
this.items = items;
return items;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
cnMain.Close();
Console.WriteLine(ex.ToString());
}
return null;
}```
From the error, I assume the exception is being raised by
item.expiryDate = reader.GetDateTime(1).ToShortDateString();
Logically, field 1 (The second column) in your StockItem table isn't a Date/Time. I'd check your table, and if you're sure that's right, maybe use reader.GetValue(1) instead, and see what you get.
enter image description hereI have two tables where in table tbl_mngr_shift_handover there mgr_handover_id is primary key and i want to insert it into another table tbl_mngr_shift_handover_details at insert time. So following is asp.net c# code
string remarkString = remarkTextArea.Content;
string query = string.Empty;
query="INSERT INTO tbl_mngr_shift_handover(msp_id,cat_id,task_id,priority_id,shift_id,status_id,activity)VALUES('"
+MSPDropDownList.SelectedValue+"','"
+CategoryDropDownList.SelectedValue+"','"
+TaskDropDownList.SelectedValue+"','"
+PriorityDropDownList.SelectedValue+"','"
+ShiftDropDownList.SelectedValue+"','"
+StatusDropDownList.SelectedValue+"','"
+ActivityTextBox.Text+"')";
string query1 ="INSERT INTO tbl_mngr_shift_handover_details(status_id,remark,inserted_by,inserted_date)"
+"VALUES('" + StatusDropDownList.SelectedValue + "','"
+ remarkTextArea.Content + "','"
+ Session["user_id"] + "','"
+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
if(query != null)
{
string query2 = "update tbl_mngr_shift_handover_details set tbl_mngr_shift_handover_details.mgr_handover_id=tbl_mngr_shift_handover.mgr_handover_id from tbl_mngr_shift_handover where tbl_mngr_shift_handover_details.mgr_handover_id=tbl_mngr_shift_handover.mgr_handover_id ";
con.ConnectionString = constr;
con.Open();
if (con != null)
{
cmd1 = new SqlCommand(query2, con);
cmd1.ExecuteNonQuery();
con.Close();
}
}
try
{
con.ConnectionString = constr;
con.Open();
if (con != null)
{
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
cmd2 = new SqlCommand(query1, con);
cmd2.ExecuteNonQuery();
PopUpLabel.Text = "Inserted Successfully";
ModalPopupExtender2.Show();
}
}
catch (Exception er)
{
// Label3.Text += "error in handover : " + er.Message;
PopUpLabel.Text = "Error While Inserting Handover.Please Concern Your Manager: Error Details: " + er.Message;
pnlPopup.Visible = true;
ModalPopupExtender2.Show();
}
finally
{
con.Close();
}
Here is database fields Images
enter image description here
Here In tbl_mngr_shift_handover_details field mgr_handover_id show null vallue so what can i do..
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
I am trying to save some data in a database using an INSERT query but it is saving double value on single click. For example I save 'Lahore', it'll save it two times:
Lahore
Lahore
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
if (dt.Read())
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
Your code is doing exactly what you told it to.
If you call an Execute*() method twice, it will run your query twice.
It's saving twice because you are executing the query twice:
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
You are saving twice.
The executeNonQuery will return the number of rows affected so use this instead.
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
var rowsAffected = query.ExecuteNonQuery();
if (rowsAffected == 1)
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
I am trying to delete a row in my users_stocks table.
I use this code:
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM " + "users_stocks" + " WHERE user_name = '" + user_name + "'" + " AND " + "stock_symbol = " + "'" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
There is a row with this data, but the query wont erase it.
What am i missing?
Use parametrized query to avoid Sql Injection Attacks and quoting problems
Not to mention that a parametrized query could be stored by the optimization engine of SqlServer and reused more quickly. An hand made query will be reevaluated every time you send to the database-
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks " +
"WHERE user_name = #name AND stock_symbol = #stock" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
cmdnon.Parameters.AddWithValue("#name", user_name);
cmdnon.Parameters.AddWithValue("#stock", stock_symbol);
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
As Luis Quijada mentioned above use parameters, they are much safer. In the code below just change the YOUR_CONNECTION_STRING value and the SqlDbType to the ones matching in your DB.
public bool removeStock(string user_name, string stock_symbol)
{
using(SqlConnection connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
using(SqlCommand command = new SqlCommand())
{
try
{
command.Connection = connection;
command.CommandText = "DELETE FROM user_stocks WHERE user_name=#USERNAME AND stock_symbol=#STOCKSYMBOL";
command.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_name.Trim();
command.Parameters.Add("#STOCKSYMBOL", SqlDbType.VarChar).Value = stock_symbol.Trim();
connection.Open();
int i = command.ExecuteNonQuery();
if (i == 0)
return false;
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
finally
{
connection.Close();
}
}
}
}
Try this code :
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks
WHERE user_name = '" + user_name + "'
AND stock_symbol = '" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
Change in query