Printing Class information C# Forms - c#

I'm trying to make a program which stores a bunch of country information from a country class in an AVL tree. I am using a form which prints out the list of countries which is saved in a CSV file and when I click on a country I want the program to print out information which corresponds to the selected country.
The problem I am having is getting it to print out the GDP in a text box when I select a country in the list box.
What code can I put to into list box which will print the gdp into a textbox?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
.
namespace country
{
public partial class Form1 : Form
{
AVLTree<Country> myTree = new AVLTree<Country>();
List<Country> Countries = new List<Country>();
static string[] headers = new string[6];
string buffer = "";
public Form1()
{
InitializeComponent();
const int MAX_LINES_FILE = 50000;
string[] AllLines = new string[MAX_LINES_FILE];
AllLines = File.ReadAllLines("countries.CSV");
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
LinkedList<string> tradePartner = new LinkedList<string>();
string[] partners = columns[5].Split(';', '[', ']');
foreach (string x in partners)
{
if (x != "")
{
tradePartner.AddLast(x);
}
}
myTree.InsertItem(new Country(columns[0], float.Parse(columns[1]), float.Parse(columns[2]), float.Parse(columns[3]), float.Parse(columns[4]), tradePartner));
}
}
myTree.PreOrder(ref buffer);
Console.WriteLine("Tree Contains " + buffer);
Add();
}
private void Add()
{
myTree.CInOrder(ref Countries);
foreach (Country y in Countries)
{
listBox1.Items.Add(y.Countryname);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
country class
public Country (string cn, float gd, float i, float tb, float hd, LinkedList<string> mt)
{
this.Countryname = cn;
this.gdp = gd;
this.inflation = i;
this.tradeBalance = tb;
this.hdi = hd;
this.mtp = mt;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return Countryname.CompareTo(temp.Countryname);
}
public override string ToString()
{
foreach (string i in mtp)
x += i + ",";
return Countryname + " " + gdp + " " + inflation + " " + tradeBalance +" " + hdi + " " + x;
}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
if (country != null )
textBox1.Text = country.gdp;
}

Related

How to transfer values to DataGridView in another Form

I'm creating a shopping application for which I need to transfer my selected items (via add to cart button) to a DataGridView in another Form so that it can show all the items that I've bought. For this I have designed a global function in my second Form so that whenever I press the "add to cart"-button in my first Form the values are added in the DataGridView in the second Form. But the code is not showing anything in the DataGridView so far.
Form1:
public partial class CLOTHES : Form
{
public static int cost = 0;
public static string name = "";
public static string size = "";
public static string NAME = "";
public static string SIZE = "";
public static int total = 0;
public CLOTHES()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
if (comboBox1.SelectedIndex == 0)
{
SIZE = "small";
label1.Text = "T-SHIRT";
cost = 300;
}
else if (comboBox1.SelectedIndex == 1)
{
SIZE = "MEDIUM";
label1.Text = "T-SHIRT";
cost = 400;
}
else if (comboBox1.SelectedIndex == 2)
{
SIZE = "LARGE";
label1.Text = "T-SHIRT";
cost = 500;
}
name = label1.Text;
size = comboBox1.SelectedIndex.ToString();
cart.populatedatagridview(name, size, cost);
nextform(cost, size, name);
}
}
void nextform(int cost, string size, string name)
{
total = cost;
NAME = name;
size = SIZE;
MessageBox.Show("total " + total);
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
cart f5 = new cart();
f5.ShowDialog();
}
}
Form2:
public partial class cart : Form
{
public cart()
{
InitializeComponent();
}
public static void populatedatagridview(string name, string size, int total)
{
cart cs = new cart();
string[] row = { "" + name, "" + size, "" + total };
cs.dataGridView1.Rows.Add(row);
}
}
See code update below, just store your cart in variable, and pass to form2 function to bind your data to gridview before displaying form2
Form1:
public partial class CLOTHES : Form
{
public static int cost = 0;
public static string name = "";
public static string size = "";
public static string NAME = "";
public static string SIZE = "";
public static int total = 0;
List<string[]> data = new List<string[]>();
public CLOTHES()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
if (comboBox1.SelectedIndex == 0)
{
SIZE = "small";
label1.Text = "T-SHIRT";
cost = 300;
}
else if (comboBox1.SelectedIndex == 1)
{
SIZE = "MEDIUM";
label1.Text = "T-SHIRT";
cost = 400;
}
else if (comboBox1.SelectedIndex == 2)
{
SIZE = "LARGE";
label1.Text = "T-SHIRT";
cost = 500;
}
name = label1.Text;
size = comboBox1.SelectedIndex.ToString();
nextform(cost, size, name);
string[] row = { "" + name, "" + size, "" + total };
data.Add(row);
}
}
void nextform(int cost, string size, string name)
{
total = cost;
NAME = name;
size = SIZE;
MessageBox.Show("total " + total);
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
cart f5 = new cart();
f5.populatedatagridview(data);
f5.ShowDialog();
}
}
Form2:
public partial class cart : Form
{
public cart()
{
InitializeComponent();
}
public void populatedatagridview(List<string[]> data)
{
foreach (var item in data)
{
dataGridView1.Rows.Add(item);
}
}
}

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?

Remove and modify a selected item from listbox that uses datasource

I have a GUI that I am creating which reads a .csv file into a listbox and I am trying to remove a country that is selected when the application is running using a button. I have tried multiple codes however nothing works I either get a error message "Items collection cannot be modified when the DataSource property is set." or nothing happens. below is what I have at the moment. I am also trying to modify a selected item using textboxes.
namespace Countries
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private IList<tradingDetails> listOfCountries;
public class tradingDetails
{
public string Country { get; set; }
public string GDP { get; set; }
public string Inflation { get; set; }
public string TB { get; set; }
public string HDI { get; set; }
public string TP { get; set; }
public string Display
{
get
{
return string.Format("Country = {0} --- GDP = {1} --- Inflation = {2} --- TB = {3} --- HDI = {4} --- TP = {5}", this.Country, this.GDP, this.Inflation, this.TB, this.HDI, this.TP);
}
}
}
public static string[] headers { get; set; }
public void load_Click(object sender, EventArgs e)
{
this.listOfCountries = new List<tradingDetails>();
this.listBox1.ValueMember = "Countries";
this.listBox1.DisplayMember = "Display";
this.InsertInfo();
this.listBox1.DataSource = this.listOfCountries;
}
public void InsertInfo()
{
OpenFileDialog browse = new OpenFileDialog();
browse.Multiselect = true;
if (browse.ShowDialog() == DialogResult.OK)
{
string selectedFile = browse.FileName;
const int MAX_SIZE = 5000;
string[] AllLines = new string[MAX_SIZE];
AllLines = File.ReadAllLines(selectedFile);
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
tradingDetails fileCountry = new tradingDetails
{
Country = columns[0],
GDP = columns[1],
Inflation = columns[2],
TB = columns[3],
HDI = columns[4],
TP = columns[5]
};
this.listOfCountries.Add(fileCountry);
}
}
}
}
private void DataBind()
{
listBox1.BeginUpdate();
listBox1.DataSource = listOfCountries;
listBox1.EndUpdate();
}
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox1.Items.RemoveAt(idx);
}
}
private void search_Click(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear();
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().Contains(textBox1.Text))
{
listBox1.SetSelected(i, true);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = listBox1.Items.Count.ToString();
}
}
}
UPDATE
I have tried this however this deletes all the information in the combo box and not an individual item.
private void remove_Click(object sender, EventArgs e)
{
comboBox1.DataSource = null;
comboBox1.Items.Remove(comboBox1.SelectedValue);
comboBox1.DataSource = listOfCountries;
}
You can't remove items from listbox while it's bounded with a source. For a better understanding, you are trying to remove the item, that your listbox is not an owner of, but the source is(that you have set the datasource of listbox).
Instead, you need to remove the item from the datasource itself.
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
//listBox1.Items.RemoveAt(idx);
listOfCountries.RemoveAt(idx)l
}
listBox1.RefreshItems();
}
Also, as you are trying to clear all the items from your listbox, this not a good approach to iterate every items and remove all. Instead, you should either clear your listOfCountries or set the listbox1datasource as null.

Regarding List<> declaration in C#

I'm trying to learn List<> in C#. I made a test program that takes the result of three textboxes and inputs it in a multiline textbox, after I put them in a list (to later save the list to file).
Here is my class declaration:
public class Film
{
public Film (string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
}
Now I instantiate the list:
List<Film> ListeFilms = new List<Film>();
And here is my event:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.ToString());
}
}
Now when I run, all that is written in the text box is:
test_1.Form1+Film
What did I do wrong?
You have to override the ToString() method in the Film class declaration.Otherwise it returns the type name.
Example:
public class Film
{
public Film(string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
public override string ToString()
{
return Numero.ToString() + " " + Titre.ToString() + " " + Categorie.ToString();
}
}
You just have to concatenate the three fields into the AppendText function:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.Numero + " - " + x.Titre + "- " + x.Categorie));
}
}

C# how to load listview

im doing a windows form application to open and load a database. the code needs to show single record view of the records and the listView view however i am stuck on the listVIew part.
here is the following code
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADOX;
namespace Ex3
{
public partial class changeButton : Form
{
public List<Client> ClientRecords = new List<Client>(); //Creates a list for the records to be stored
public string filename;
public string fileDir;
public string rec;
public bool checkBC;
public bool checkLC;
public string dataBaseFile;
public OleDbConnection conn;
public changeButton()
{
InitializeComponent();
}
int position = 0;
private void Form1_Load(object sender, EventArgs e)
{
credBalBox.Maximum = 9999999999;
savingBalBox.Maximum = 9999999999;
}
private void ConnectToDataBase()
{
try
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
dataBaseFile + ";";
conn = new OleDbConnection(strConn);
conn.Open();
}
catch (OleDbException e)
{
MessageBox.Show("Failed to connect to database: " + e.Message);
}
}
private void nextButton_Click(object sender, EventArgs e)
{
if (position < ClientRecords.Count - 1)
{
position++;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
private void previousButton_Click(object sender, EventArgs e)
{
if (position > 0)
{
position--;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
public void Print()
{
int positionAdd1;
positionAdd1 = position;
positionAdd1++;
currentRecLab.Text = positionAdd1.ToString();
MaxRecLab.Text = ClientRecords.Count.ToString();
if (position >= 0 && position < ClientRecords.Count)
{
nameBox.Text = ClientRecords[position].Name;
suburbBox.Text = ClientRecords[position].Suburb;
postBox.Text = ClientRecords[position].Postcode;
credBalBox.Text = ClientRecords[position].CreditBal.ToString();
savingBalBox.Text = ClientRecords[position].SavingBal.ToString();
}
else
{
nameBox.Text = "";
suburbBox.Text = "";
postBox.Text = "";
credBalBox.Text = "";
savingBalBox.Text = "";
}
}
private void addButton_Click(object sender, EventArgs e)
{
string sameAddName = "null";
string addName;
string addSuburb;
string addPostcode;
decimal addCredBal;
decimal addSavBal;
addName = nameBox.Text;
addSuburb = suburbBox.Text;
addPostcode = postBox.Text;
addCredBal = decimal.Parse(credBalBox.Text);
addSavBal = decimal.Parse(savingBalBox.Text);
string sqlPrefix = "INSERT INTO Client VALUES ";
string data = "(" + "'" + addName + "','" + addSuburb + "','" + addPostcode + "','" + addCredBal + "','" + addSavBal + "'" + ")";
string sql = sqlPrefix + data;
foreach (Client client in ClientRecords)
{
if (addName == client.Name)
{
sameAddName = "Name is not unique. Please use a unique name";
}
}
if (sameAddName == "null" && addSuburb != null)
{
ClientRecords.Add(new Client(addName, addSuburb, addPostcode, addCredBal, addSavBal));
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
int positions = ClientRecords.Count;
currentRecLab.Text = positions.ToString();
MaxRecLab.Text = positions.ToString();
nameBox.Text = addName;
suburbBox.Text = addSuburb;
postBox.Text = addPostcode;
credBalBox.Text = addCredBal.ToString();
savingBalBox.Text = addSavBal.ToString();
position = ClientRecords.Count - 1;
}
else
{
if ((sameAddName != "null") && (addSuburb == "") && (addPostcode == ""))
{
MessageBox.Show(sameAddName + "\nAlso, one of the fields are empty. Please fill it in before adding a new record");
}
else if (sameAddName != "null")
{
MessageBox.Show(sameAddName);
}
}
}
private void removeButton_Click(object sender, EventArgs e)
{
int recPosition = int.Parse(currentRecLab.Text);
recPosition = recPosition - 1;
position = 0;
ClientRecords.Remove(ClientRecords[recPosition]);
Print();
if (MaxRecLab.Text == "0")
{
currentRecLab.Text = "0";
}
}
private void loadButton_Click_1(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand ("SELECT * FROM Client", conn);
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Client nClient = new Client(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), decimal.Parse(rdr[3].ToString()), decimal.Parse(rdr[4].ToString()));
ClientRecords.Add(nClient);
Print();
}
}
}
private void connectButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select DataBase";
if (dialog.ShowDialog() == DialogResult.OK)
{
dataBaseFile = dialog.FileName;
DatabaseNameBox.Text = dataBaseFile;
ConnectToDataBase();
}
}
private void DatabaseNameBox_TextChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void nameBox_TextChanged(object sender, EventArgs e)
{
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
public class Client
{
protected string name;
protected string suburb;
protected string postcode;
protected decimal creditBal;
protected decimal savingBal;
public Client(string name, string suburb, string postcode, decimal creditBal, decimal savingBal)
{
this.name = name;
this.suburb = suburb;
this.postcode = postcode;
this.creditBal = creditBal;
this.savingBal = savingBal;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Suburb
{
get
{
return suburb;
}
set
{
suburb = value;
}
}
public string Postcode
{
get
{
return postcode;
}
set
{
postcode = value;
}
}
public decimal CreditBal
{
get
{
return creditBal;
}
set
{
creditBal = value;
}
}
public decimal SavingBal
{
get
{
return savingBal;
}
set
{
savingBal = value;
}
}
}
}
thanks in advance
further info
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
i want to be able to put the code here and when i click the load button from above it should load the listview
To load a listview I would use the following function - it uses a array of string and listviewitem do add items to a listview.
private void LoadListview()
{
string NAME = "John DOE";
string AGE = "30";
string SEX = "MALE";
string DOB = "08/28/1988";
string[] rowa = { NAME, AGE, SEX, DOB };
var listViewItema = new ListViewItem(rowa);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
}
You can find a step by step detail answer on my website: http://softvernow.com/2018/05/01/create-list-of-objects-and-load-listview-using-c/

Categories