I want to create chart that read the Extra_Process column in my database..It only have two value. "Rush Order" and "Normal Order"
i have this code...
chart1.Series["Order Process"].Points.Clear();
MySqlCommand cmd = new MySqlCommand("SELECT Extra_Process, sum(Extra_Process) qty FROM sketchit.monitoring GROUP BY Extra_Process; ", dc.con);
MySqlDataReader myreader;
try
{
dc.con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
this.chart1.Series["Order Process"].Points.AddXY(myreader.GetString("Extra_Process"), myreader.GetInt32("qty"));
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
dc.con.Close();
I want to know how many rush order and normal order in my column but it doesn't show any result. I don't know what to do.
here's the pic
Steps:
Query and get the Count value of both RushOrder and NormalOrder.
Once you get the both count pass it to the following function to generate the PieChart
private void btnChart_Click(object sender, EventArgs e)
{
//Make your Query , Get Count Value for RushOrder and NormalOrder
//Check for Null Value
//Pass the Count to the DrawPieChart() function
//Sample Chart Generation
int nRushOrderCount = Convert.ToInt32(txtRushOrder.Text);
int nNormalOrderCount = Convert.ToInt32(txtNormalOrder.Text);
DrawPieChart(nRushOrderCount, nNormalOrderCount);
}
private void DrawPieChart(int nRushOrder, int nNormalOrder)
{
//reset your chart series and legends
chart1.Series.Clear();
chart1.Legends.Clear();
//Add a new Legend(if needed) and do some formating
chart1.Legends.Add("MyLegend");
chart1.Legends[0].LegendStyle = LegendStyle.Table;
chart1.Legends[0].Docking = Docking.Bottom;
chart1.Legends[0].Alignment = StringAlignment.Center;
chart1.Legends[0].Title = "Order Details";
chart1.Legends[0].BorderColor = Color.Black;
//Add a new chart-series
string seriesname = "MySeriesName";
chart1.Series.Add(seriesname);
//set the chart-type to "Pie"
chart1.Series[seriesname].ChartType = SeriesChartType.Pie;
//Add some datapoints so the series. in this case you can pass the values to this method
chart1.Series[seriesname].Points.AddXY("Rush Order", nRushOrder);
chart1.Series[seriesname].Points.AddXY("Normal Order", nNormalOrder);
chart1.Series[seriesname].IsValueShownAsLabel = true;
}
Related
private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True";
int txtno = int.Parse(textBox1.Text);
int pointX = 30;
int pointY = 40;
panel2.Controls.Clear();
for (int i = 0; i < txtno; i++)
{
TextBox a = new TextBox();
a.Text = (i + 1).ToString();
a.Location = new Point(pointX, pointY);
panel2.Controls.Add(a);
panel2.Show();
pointY += 20;
}
string Query = "select task_comment from test123.task_comment where task_id ='" + textBox1.Text + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
MyConn2.Close();
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
txtno = Convert.ToInt32(MyReader2["task_comment"].ToString());
}
MyConn2.Close(); //Connection closed here
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try This:
protected void Page_Load(object sender, EventArgs e)
{
int n = 4;//fetch your rows from database in datatable, then count number of rows. And based on those
//count create textboxes.
TextBox[] textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
textBoxes[i].Text="Your text from database";
}
}
Hope this helps!
Suppose you have the data retrieved from MySql in a list of object with propertis ID and Name, so you loop over them and create a textbox and add it to the form:
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
txtno = Convert.ToInt32(MyReader2["task_comment"].ToString());
TextBox bx = new TextBox();
bx.Text = txtno;
// retrieve here any other data u need to assign to the textbox
bx.Location = new Point(x, y);// x and y should be the calculated //coordinates, this will depend on how you want to display the textboxes
this.Controls.Add(bx);// Add the textbox to the form
}
MyConn2.Close(); //Connection closed here
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Im trying to show gender percentage into a pie chart using count statement and placing it in dataset. Ive retrived the data but i have no idea on how to bind it in XY because all the data is in a single dataTable variable.
So my flow for the program,
user choose table name from drop down list
user generate report
ddl for x and y is filled with column shown in the report above
user choose the x and y value which has the column name from the ddl
For the database, it only have id, name and gender.
If it is just reading the value from DB, then i have managed to do it using dataView(), but for this i really dont know how to do it.
p/s. new in C# and asp.net. Appreciate all the help and TQVM in advanced.
1st part code - taking user drop down list and creating the dataset
public void testGraph()
{
string ddlX = ddlTestGraphX.SelectedValue;
string ddlY = ddlTestGraphY.SelectedValue;
CodeDB db = new CodeDB();
db.Open();
//SET UP THE DATA TO PLOT
string userInput = DDLTableName.SelectedValue;
if (userInput == "tblparticipant")
{
DataSet dsX = db.getDataSet2(ddlX, userInput);
DataTable dataX = dsX.Tables[0];
DataSet dsY = db.getDataSetCount(ddlY, userInput);
DataTable dataY = dsY.Tables[0];
string trimmedUserInput = userInput.Remove(0, 3);
try
{
if (rbPieChart.Checked == true)
{
pieChart(trimmedUserInput, dataX, dataY);
}
}
catch (Exception ex)
{
lblError.Visible = true;
lblError.Text = "Check Your drop down list";
}
}
}
2nd part code - displaying the pie chart
public void pieChart(string recTrimmedUserInput, DataTable recDataX, DataTable recDataY)
{
//BIND THE DATA TO THE CHART
Chart1.Series.Add(new Series());
Title title = Chart1.Titles.Add("CHART " + recTrimmedUserInput.ToUpper());
Chart1.Series[0].Points.DataBindXY(recDataX.AsDataView(), recDataY.AsDataView());
//SET THE CHART TYPE TO BE PIE
Chart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie;
//Chart1.Series[0].Label = "#PERCENT{P2}";
Chart1.Series[0]["PieLabelStyle"] = "Outside";
Chart1.Series[0]["PieStartAngle"] = "-90";
//SET THE COLOR PALETTE FOR THE CHART TO BE A PRESET OF NONE
//DEFINE OUR OWN COLOR PALETTE FOR THE CHART
Chart1.Palette = System.Web.UI.DataVisualization.Charting.ChartColorPalette.None;
//Chart1.PaletteCustomColors = new Color[] { Color.Blue, Color.Red };
//Chart1.Series[0].Label = "#VALX , #VALY";
Chart1.Series[0].Label = "#PERCENT{P2}";
//SET THE IMAGE OUTPUT TYPE TO BE JPEG
Chart1.ImageType = System.Web.UI.DataVisualization.Charting.ChartImageType.Jpeg;
//ADD A PLACE HOLDER CHART AREA TO THE CHART
//SET THE CHART AREA TO BE 3D
Chart1.ChartAreas.Add(new ChartArea());
Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
//ADD A PLACE HOLDER LEGEND TO THE CHART
//DISABLE THE LEGEND
Chart1.Legends.Add(new Legend());
Chart1.Series[0].LegendText = "#VALX";
Chart1.Legends[0].Enabled = true;
}
3rd part code - getting dataset
public DataSet getDataSetCount(string receivedDDL, string receivedUserInput)
{
string query = "Select " + receivedDDL +", count(id) as count From "+ receivedUserInput+" Group by "+ receivedDDL;
if (con.State.ToString() == "Open")
{
SqlDataAdapter ad = new SqlDataAdapter(query, con);
DataSet ds = new DataSet("Table");
ad.Fill(ds);
return ds;
}
else
{
return null;
}
}
I've done some research and I've managed to found information about drawing a graph where you hard code a Data Table with fixed values.
This is the link: How to create chart using data table
My problem is however;
I don't have a Data Table like that. I have DataAccess class that call the data from a database then stores it in a Data Table;
public DataTable select_top_sheep(string farmerid)
{
dt = new DataTable();
try
{
conn.Open();
SqlCommand cmd =
new SqlCommand("SELECT TOP 10
S.SheepID
,W.Weight
FROM[Farmstat_V1.0].[dbo].[Sheep] S
INNER JOIN[Farmstat_V1.0].[dbo].[Weight] W
ON S.SheepID = W.SheepID
WHERE S.FarmerID = '" + farmerid + "'
ORDER BY W.Weight DESC", conn);
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
return dt;
}
Then on my form I call this method to get the data, but how can I from here display it in a graph? I can see that the data stores successfully in the DataTable when I run the program in debug mode.
I just want to use the basic Chart tool from the toolbox to display the data graphically.
I have managed to figure out the answer with the use of the link I provided in my question.
This is what I did;
protected void Page_Load(object sender, EventArgs e)
{
// Initializes a new instance of the DataAccess class
DataAccess da = new DataAccess();
// The styling of the graph
chart1.Series["Series1"].ChartType = SeriesChartType.Column;
chart1.Series["Series1"].IsValueShownAsLabel = true;
// The required lines for getting the data from the method in the DataAccess
chart1.DataSource = da.select_top_sheep(farmerID);
chart1.Series["Series1"].XValueMember = "SheepID";
chart1.Series["Series1"].YValueMembers = "Weight";
chart1.DataBind();
}
Just need to google it:
Chart sample
public void SampleCode()
{
// some code
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
// For each Row add a new series
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
// For each column (column 1 and onward) add the value as a point
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
int YVal = (int)row[columnName];
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
DataGrid.DataSource = myDataSet;
DataGrid.DataBind();
}
I am using datagrid view in a windows form application. I have several data grids that display a date date column. When I display my data, the date shows correctly but is always followed by '00:00:00'. How can I change it to only display the date as 'dd/mm'yyyy'.
I build my datagrid as follows:
//Populate customers datagrid view
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = customersDataGridView.Rows.Add();
// datagridname.row[index].cells.value = reader[table].tostring()
customersDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
customersDataGridView.Rows[arow].Cells[1].Value = reader["Forename"].ToString();
customersDataGridView.Rows[arow].Cells[2].Value = reader["Surname"].ToString();
customersDataGridView.Rows[arow].Cells[3].Value = reader["Address"].ToString();
customersDataGridView.Rows[arow].Cells[4].Value = reader["Town"].ToString();
customersDataGridView.Rows[arow].Cells[5].Value = reader["Postcode"].ToString();
customersDataGridView.Rows[arow].Cells[6].Value = reader["Date_Of_Birth"].ToString();
customersDataGridView.Rows[arow].Cells[7].Value = reader["Phone_Number"].ToString();
customersDataGridView.Rows[arow].Cells[8].Value = reader["Email"].ToString();
customersDataGridView.Rows[arow].Cells[9].Value = reader["Current_Rental"].ToString();
customersDataGridView.Sort(Surname, ListSortDirection.Ascending);
}
reader.Close();
connect.Close();
}
//Display all customers button
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
Also, I have another problem in a different datagrid. This one has a payment column and when I originally created the table in access, the data in the column was like '£4.99' and right justified as expected but when I display it, there is no '£' symbol and it is left justified.
Code for that datagrid is:
//Populate payments datagrid view
private void displayInGrid_Payments(string sqlcmd)
{
paymentsDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = paymentsDataGridView.Rows.Add();
paymentsDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString();
paymentsDataGridView.Rows[arow].Cells[2].Value = reader["Payment_Date"].ToString();
}
reader.Close();
connect.Close();
}
//Display all payments
private void button_display_payments_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT PAYMENTS.Customer_ID, PAYMENTS.Payment, PAYMENTS.Payment_Date "
+ "from PAYMENTS LEFT JOIN CUSTOMERS ON PAYMENTS.Customer_ID = CUSTOMERS.Customer_ID";
string cmd = command.CommandText;
displayInGrid_Payments(cmd);
}
For the first part try:
customersDataGridView.Rows[arow].Cells[6].Value = ((DateTime)reader["Date_Of_Birth"]).ToShortDateString()
And for the second part try:
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString("C");
paymentsDataGridView.Rows[arow].Cells[1].Value = String.Format("{0:C}", decimal.Parse(reader["Payment"].ToString()));
If it still gives error, try changing decimal for double, although for money and currency I would avoid double because of rounding errors it could give.
How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb"))
using(OleDbCommand cmd = new OleDbCommand(" SELECT * from TableAcct", conn))
{
conn.Open();
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
listBox1.Text = Reader.GetString("FirstName");
}
}
the errors are here:
1. Error 1 The best overloaded method match for'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments.
2. Error 2 Argument '1': cannot convert from 'string' to 'int'
try this one,
List<String> firstName = new List<String>();
List<String> lastName = new List<String>();
private void loadButton_Click(object sender, EventArgs e)
{
cn.Open();
OleDbDataReader reader = null;
cmd = new OleDbCommand("select* from Records", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
firstName.Add(reader["FirstName"].ToString());
lastName.Add(reader["LastName"].ToString());
}
cn.Close();
}
then in your search button, insert this,
private void searchButton_Click(object sender, EventArgs e)
{
clearSearchResult();
try
{
int totalItems = FirstName.Count;
int count = 0;
while (count < totalItems)
{
if (textBox6.Text == FirstName[count].ToString())
{
listBox1.Items.Add(FirstName[count].ToString());
count = 100;
}
else
{
count++;
}
It's good to use when you want to show the information of the "FirstName" in the listBox1_SelectedIndexChanged if you want. here's an example,
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int totalItems = lastName.Count;
int count = 0;
while (count < totalItems)
{
if ((listBox1.SelectedItem.ToString()) == firstName[count].ToString()))
{
textBox1.Text = firstName[count].ToString();
textBox2.Text = lastName[count].ToString();
count = 100;
}
else
{
count++;
}
}
hope this helps,
change
listBox1.Text = Reader.GetString("FirstName");
to
listBox1.Text = Reader.GetString(0); // zero base ordinal of column
GetString() takes an int as the parameter and not a string. Meaning that you must use the index of the column.
In your specific circumstance as "FirstName" is the second column the index would be 1:
listBox1.Text = Reader.GetString(1);
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
Thy using a While loop
while(reader.Read())
{
listbox1.Items.Add(reader["FirstName"]);
}
This moves through all the rows you selected. reader.Read() returns false if there are no more rows.
Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader instance. Like my example.
var value = reader["ColumnName"];
This increases readability comparing to
var value = reader.GetString(0);
UPDATE
If you want to only display the fist value - I suggest you use cmd.ExecuteScalar() and the adapt you sql to only return the value you need:
using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
{
conn.Open();
var firstName = cmd.ExecuteScalar();
}
Be aware the this will give you the first "FirstName" in the table. And since there is no "order by firstname" or "where someKey = 1" - this might not rturn that you expected.
If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label.
First of all create any Access data base like here "PirFahimDataBase".
Now in your Visual Studio go to the menu and do this
Click Data
Add New Data Base
Click Next
Click New Connection
Now change the Data Source by clicking Change and select Microsoft Access data base files
Click Browse for selecting your created data base
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
using System.Windows.Forms; //these two lines should be written before namespace at top of the program
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
try
{
conn.Open();
MessageBox.Show("connected successfuly");
OleDbDataReader reader = null; // This is OleDb Reader
OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label1.Text= reader["TicketNo"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}//end of button click event
Your error is in this line:
listBox1.Text = Reader.GetString("FirstName");
You must pass a number in the GetString() function.
DataColumn[] PrimaryKeyColumn = new DataColumn[1]; //Define Primary coloumn
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
ReadAndUpdateExcel.ReadExcel(strPath, sheetName, out dataSet);
dataSet.Tables.Add(dataTable);
PrimaryKeyColumn[0] = dataSet.Tables[0].Columns[0];
dataSet.Tables[0].PrimaryKey = PrimaryKeyColumn;
string num = dataSet.Tables[0].Rows[dataSet.Tables[0].Rows.IndexOf(dataSet.Tables[0].Rows.Find(strTCName))]["ACNO"].ToString();
//string country