Databind chart with members from a field instance - c#

I would like to put chart series in a List so that I can add new series dynamically. But I have not been able to figure out how to bind the data to the chart when it is structured like this. Maybe its not possible or there are better ways?
public class DataSerie {
public DataSerie(string _name, double _value) {
name = _name;
value = _value;
}
public string name { get; set; }
public double value { get; set; }
}
public class ChartData
{
public ChartData(double _x)
{
x = _x;
series = new List<DataSerie>();
}
public double x { get; set; }
public List<DataSerie> series { get; set; }
}
private List<ChartData> chartDataList = new List<ChartData>();
private void Form1_Load(object sender, EventArgs e)
{
ChartData cd;
cd = new ChartData(1);
cd.series.Add(new DataSerie("y1", 5));
cd.series.Add(new DataSerie("y2", 3));
cd.series.Add(new DataSerie("y3", 3));
chartDataList.Add(cd);
cd = new ChartData(2);
cd.series.Add(new DataSerie("y1", 5));
cd.series.Add(new DataSerie("y2", 4));
cd.series.Add(new DataSerie("y3", 2));
chartDataList.Add(cd);
chart1.DataSource = chartDataList;
chart1.Series.Clear();
ChartData c = chartDataList[0];
foreach (DataSerie serie in c.series) {
chart1.Series.Add(serie.name);
chart1.Series[serie.name].XValueMember = "X";
chart1.Series[serie.name].YValueMembers = "serie.value"; // This obviously doesnt work.
}
}

I solved it by iterating over the data and populate the chart like this: chart.Series[serie.name].Points.AddXY(data.x,data.y);
Instead of databinding

Related

Change value in a list that is binded?

I'm pretty new at this. Using Windows Forms in Visual Studio. I am to hammer out a store that has clothes, with stock that can be transferred in or out of the store.
I've gotten as far as to having a class, a list that contains the clothes and their quantities, and I've managed to get them into comboboxes. What I want to do now is to be able to 'buy' new quantities, changing the value in the list.
I'm stumped as to how to change the actual quantities, I'm sure I am missing stuff here.
This is my class:
public class Store
{
public string Clothing { get; set; }
public int Quantity { get; set; }
public Store(string c, int q)
{
Clothing = c;
Quantity = q;
}
And this is my current code:
}
public partial class Form1 : Form
{
List<Store> stock = new List<Store>
{
new Store ("Jeans size S", 1),
new Store ("Jeans size M", 3),
new Store ("Jeans size L", 5)
};
public Form1()
{
InitializeComponent();
}
private void bShow_Click(object sender, EventArgs e)
{
cbStockType.ValueMember = "Clothing";
cbStockType.DisplayMember = "Clothing";
cbStockType.DataSource = stock;
cbStockQnt.ValueMember = "Quantity";
cbStockQnt.DisplayMember = "Quantity";
cbStockQnt.DataSource = stock;
}
private void lblHighlightAdd_Click(object sender, EventArgs e)
{
}
private void bSlctClothing_Click(object sender, EventArgs e)
{
if (cbStockType.SelectedIndex < 0)
{ lblHighlightAdd.Text = "None"; }
else
lblHighlightAdd.Text = cbStockType.SelectedValue.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string quantityToAdd = tbQntAdd.Text;
int add = Convert.ToInt32(quantityToAdd);
string addToStock = cbStockQnt.SelectedValue.ToString();
int newAmount = Convert.ToInt32(addToStock);
int result = newAmount + add;
foreach (var item in stock)
{
if (item.Clothing == cbStockType.SelectedValue.ToString())
{
item.Quantity = item.Quantity + result;
MessageBox.Show(cbStockQnt.SelectedValue.ToString());
}
}
}
}
}
If you can read this spaghetti junk, I'm stuck at getting the quantity of the selected piece of clothing to change. How do I get it to change the value both in the list and in the combobox?

List sorting troubles

I have a list of programmers:
programmers.Add(new Programmer("Jake", 1.9, 2000));
programmers.Add(new Programmer("Richard", 1.0, 1300));
and I need to create a new list of sorted programmers by this
value => 2000 / 1.9.(upward)
I can't figure out how to divide int by double and sort the programmers by this result. Can you please help me how to do so?
So far I've tried:
var ProgrammersSorted = programmers.OrderBy((x,y) => x.DailyWage / y.Speed).ToList();
Programmer class:
public class Programmer
{
public string Name { get; private set; }
public double Speed { get; private set; }
public int DailyWage { get; private set; }
public Project Project { get; private set; }
public string ProjectName
{
get
{
return Project?.Name ?? "No project assigned";
}
}
public Programmer(string name, double speed, int dailyWage)
{
Name = name;
Speed = speed;
DailyWage = dailyWage;
}
}
You are very close. Try this out:
var programmersSorted = programmers.OrderBy(x => x.DailyWage / x.Speed).ToList();
Please try below code, I think this will solve your issue.
var programmers = new List<Programmer>
{
new Programmer("SS",12.3,2345),
new Programmer("ADE",1.21,22345),
new Programmer("AR",12.2,23445),
new Programmer("NK",12.5,23455)
};
var progrmrs = programmers.OrderBy(t => t.DailyWage / t.Speed).ToList();
Console.WriteLine("Name\t Speed\t DailyWage");
foreach (var prgrm in progrmrs)
{
Console.WriteLine("{0}\t {1}\t {2}", prgrm.Name, prgrm.Speed, prgrm.DailyWage);
}

Increment through property names in object

I have the following object:
namespace BluetoothExample
{
public class Assay
{
public double Band_1 //Vis450
{
get;
set;
}
public double Band_2 //Vis500
{
get;
set;
}
public double Band_3 //Vis550
{
get;
set;
}
public double Band_4 //Vis570
{
get;
set;
}
}
}
I want to populate the 4 bands in my object. Which I currently do in the following way:
public Populate()
{
int _i = 0;
double[] nirData = new double[4];
MyDevice.Characteristic.ValueUpdated += (sender, e) =>
{
nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
_i++;
};
Assay assay = new Assay();
assay.Band_1 = nirData[0];
assay.Band_2 = nirData[1];
assay.Band_3 = nirData[2];
assay.Band_4 = nirData[3];
}
I was wondering if it was possible to do the entire thing inside the MyDevice.Characteristic.ValueUpdate method instead? My thought is that it should be possible to increment and populate the properties of my object like so:
string name = "assay.Band_" + _i;
name = BitConverter.ToDouble(e.Characteristic.Value, 0);
This is obviously wrong, but it sort of demonstrates my idea.
Just make your band an Array, or List:
public class Assay
{
public double[] Band
{
get;
set;
}
}
And then you can simply assign it like:
public Populate()
{
int _i = 0;
double[] nirData = new double[4];
MyDevice.Characteristic.ValueUpdated += (sender, e) =>
{
nirData[_i] = BitConverter.ToDouble(e.Characteristic.Value, 0);
_i++;
};
Assay assay = new Assay();
assay.Band = nirData;
}

how to save value in listview from other form

Im having a problem in my listview because whenever I get value in other form it is not adding on the list but when I put breakpoint it have a value but still not adding on my listview.
here is my function in form1 getting values from datagridview
public void dataGridView1_DoubleClick(object sender, EventArgs e)
{
qtyOfOrders orders = new qtyOfOrders();
if (dataGridView1.SelectedRows.Count > 0)
{
String mealname = dataGridView1.SelectedRows[0].Cells[1].Value + String.Empty;
String price1 = dataGridView1.SelectedRows[0].Cells[2].Value + String.Empty;
pts.meal = mealname;
pts.qtyprice = Int32.Parse(price1);
orders.Show();
}
}
here is my function from form2 and will save data in listview in form1
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
c.listView1.Items.Add(pts.meal);
c.qtyOrder.ListView.Items[0].SubItems.Add(pts.qtynumber.ToString());
c.price111.ListView.Items[0].SubItems.Add(pts.TotalPrice.ToString());
this.Hide();
}
this is my class
namespace jollibee4
{
class pricetempstorage
{
static int qtyNumber;
static int qtyPrice;
static int ListViewCount;
static String Meal;
static int totalprice;
public int TotalPrice
{
get
{
return totalprice;
}
set
{
totalprice = qtyNumber * qtyPrice;
}
}
public int qtynumber
{
get
{
return qtyNumber;
}
set
{
qtyNumber = value;
}
}
public int qtyprice
{
get
{
return qtyPrice;
}
set
{
qtyPrice = value;
}
}
public int listviewCount
{
get
{
return ListViewCount;
}
set
{
ListViewCount = value;
}
}
public String meal
{
get
{
return Meal;
}
set
{
Meal = value;
}
}
}
}
Try adding this code this.listView1.View = View.Details; After the c.listView1.Items.Add(pts.meal);
form1
public List<pricetempstorage> Items { get; private set; }
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
Items.Add(pts);
this.Hide();
}
Create a shopping cart class where items can be append in list
I assume pricetempstorage is your class of item, its name can be product
public static ShoppingCart GetInstance()
{
if (cart == null)
{
cart = new ShoppingCart();
}
return cart;
}
protected ShoppingCart()
{
Items = new List<pricetempstorage>();
}
You have many architectural and stylistic issues with your program (use of static, capitalization, etc.)--to correct them all would require a very lengthy response.
Your code isn't working because you're creating a new instance of the cashier class, and then you're updating its listView1 object. What I think you're trying to do is update the listView object of Form2. So what you should be doing is grabbing a reference to Form2 and populating its ListView object in your OK_Click event handler...
Just a tip here: Public properties should have an initial capital letter. Your pricetempstorage class needs some work.

Diplaying AVL Tree data in a GUI C#

Basically I have an AVL tree that stores instances of Country class. When I do an inorder traversal of the tree, I am able to see the country details correctly, however I wish to view and modify instances of the country class in a GUI. The issue I am having is I have no idea how to access the class data and display it in something like a listbox. Here is my Country class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace International_Trading_Data
{
class Country : IComparable
{
public string countryName { get; set; }
public double gdp { get; set; }
public double inflation { get; set; }
public double tradeBalance { get; set; }
public int hdiRanking { get; set; }
public LinkedList<string> tradePartners { get; set; }
public string f;
public Country (){
}
public Country(string cname, double g, double i, double t, int h, LinkedList<string> tp)
{
this.countryName = cname;
this.gdp = g;
this.inflation = i;
this.tradeBalance = t;
this.hdiRanking = h;
this.tradePartners = tp;
}
public int CompareTo(object obj)
{
Country temp = (Country)obj;
return countryName.CompareTo(temp.countryName);
}
public override string ToString()
{
foreach (string i in tradePartners)
f += i+",";
return countryName+" "+gdp+" "+" "+inflation+" "+tradeBalance+" "+ hdiRanking+ " "+f;
}
}
}
`
This is where I create instances of the country class:
public void loadFile()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "CSV Files (*.csv)|*.csv";
open.FilterIndex = 1;
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
string selectedFilePath = open.FileName;
const int MAX_SIZE = 5000;
string[] allLines = new string[MAX_SIZE];
allLines = File.ReadAllLines(selectedFilePath);
foreach (string line in allLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
LinkedList<string> tradePartners = new LinkedList<string>();
string[] partners = columns[5].Split('[', ']', ';');
foreach (string i in partners)
{
if (i != "")
{
tradePartners.AddLast(i);
}
}
countries.InsertItem(new Country(columns[0], Double.Parse(columns[1]),Double.Parse(columns[2]), Double.Parse(columns[3]) ,int.Parse(columns[4]),tradePartners));
}
}
Here is the code for my inorder traversal:
public void InOrder()
{
inOrder(root);
}
private void inOrder(Node<T> tree)
{
if (tree != null)
{
inOrder(tree.Left);
System.Diagnostics.Debug.WriteLine(tree.Data.ToString());
inOrder(tree.Right);
}
This code produces the following output for a few test countries:
Argentina 3 22.7 0.6 45 Brazil,Chile,
Australia 3.3 2.2 -5 2 China,Japan,New_Zealand,
Brazil 3 5.2 -2.2 84 Chile,Argentina,USA,
So I know that my classes are bieng stored correctly in the avl tree.
I am not sure what you are using as a data structure for your countries collection, but assuming its a List for now, you can do the following (NOTE: this sample is just to demonstrate displaying information on a UI for manipulation):
public Form1()
{
InitializeComponent();
List<Country> countries = new List<Country>() {
new Country() { countryName = "Mattopia" , gdp = 1500, inflation = 1.5, f="hi"},
new Country { countryName = "coffeebandit", gdp = 2000, inflation = 1.2, f="hey" }};
listBox1.DisplayMember = "countryName";
listBox1.DataSource = countries;
}
public class Country
{
public string countryName { get; set; }
public double gdp { get; set; }
public double inflation { get; set; }
public double tradeBalance { get; set; }
public int hdiRanking { get; set; }
public LinkedList<string> tradePartners { get; set; }
public string f;
}
Then, you can use the selected index changed event to populate your fields:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
//fill up all other GUI controls
textBox1.Text = country.f;
textBox2.Text = country.inflation.ToString();
}
And if you want to process text changes:
private void textBox1_TextChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
if (country != null)
{
country.f = textBox1.Text;
}
}
This will give you the following display:
This should demonstrate the basics of how to edit a class in a WinForms UI.
For more advanced examples, I would recommend using other Events to capture information as your needs change.

Categories