Storing a value to a listbox item C# - c#

I wish to know how to store a VALUE to an item in a listbox. I'm currently working out a worksheet for my studies, and I've been wondering how to do this. Basically I need to store values to the Food (such as broccoli, bread. For example: Broccoli has a value of 20 calories).
The user must not see the value, only the program can store it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MCAST_Calorie_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
lbAvailable.Items.Clear();
if (comboBox1.Text == "Vegetables")
{
lbAvailable.Items.Add("Broccoli");
lbAvailable.Items.Add("Carrots");
lbAvailable.Items.Add("Lettuce");
lbAvailable.Items.Add("Onions");
lbAvailable.Items.Add("Potatoes");
}
if (comboBox1.Text == "Meat")
{
lbAvailable.Items.Add("Chicken");
lbAvailable.Items.Add("Veal");
lbAvailable.Items.Add("Beef");
lbAvailable.Items.Add("Fish");
}
if (comboBox1.Text == "Legumes")
{
lbAvailable.Items.Add("Bread");
lbAvailable.Items.Add("Peanuts");
lbAvailable.Items.Add("Green Peas");
lbAvailable.Items.Add("Lentils");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListBox.SelectedObjectCollection highlightedItems = lbAvailable.SelectedItems;
foreach (var item in highlightedItems)
{
lbChosen.Items.Add(item);
}
if (lbAvailable.SelectedItems.Count > 0)
{
lbAvailable.Items.Remove(lbAvailable.SelectedItems[0]);
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
ListBox.SelectedObjectCollection highlightedItems = lbChosen.SelectedItems;
foreach (var item in highlightedItems)
{
lbAvailable.Items.Add(item);
}
if (lbChosen.SelectedItems.Count > 0)
{
lbChosen.Items.Remove(lbChosen.SelectedItems[0]);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
lbAvailable.Items.Clear();
lbChosen.Items.Clear();
if (comboBox1.Text == "Vegetables")
{
lbAvailable.Items.Add("Broccoli");
lbAvailable.Items.Add("Carrots");
lbAvailable.Items.Add("Lettuce");
lbAvailable.Items.Add("Onions");
lbAvailable.Items.Add("Potatoes");
}
if (comboBox1.Text == "Meat")
{
lbAvailable.Items.Add("Chicken");
lbAvailable.Items.Add("Veal");
lbAvailable.Items.Add("Beef");
lbAvailable.Items.Add("Fish");
}
if (comboBox1.Text == "Legumes")
{
lbAvailable.Items.Add("Bread");
lbAvailable.Items.Add("Peanuts");
lbAvailable.Items.Add("Green Peas");
lbAvailable.Items.Add("Lentils");
}
}
}
}
Thanks alot for your help!

You can always add custom objects that support ToString() to the ListBox.Items collection:
struct Record
{
int value;
string label;
public override string ToString()
{
return label;
}
}
Adding a custom object:
Record record = new Record();
record.value = 1;
record.label = "This text will appear in the ListBox";
listBox.Items.Add(record);
Retrieving it:
Record selectedRecord = (Record)listBox.SelectedItem;
Console.WriteLine(selectedRecord.value); // => 1

Related

Passing data between two forms

first of all i want you to know that i know that there a lot of results for this question, but i have searched far and wide still haven't come up with a solution for my problem.
i have tried to do the following:
1.constructor
2.objects
3.properties
4.delegates
but none of my implementation of them really did worked as wanted (in this "solution" i have used properties
when i press "back" on the "pop up" screen i dont in the main screen the value i choose from in the "pop up" screen
basically, it's something like, i have main screen and a "pop up"
the main screen
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BakaritCV
{
public partial class FrmProdChoose : MetroFramework.Forms.MetroForm
{
CVFeedUtilities utilities = new CVFeedUtilities();
Mixtures mixture;
public string selectedDefault = " 102";
string t;
public FrmProdChoose(string t)
{
InitializeComponent();
this.t = t;
}
public FrmProdChoose()
{
InitializeComponent();
}
private void btnHome_Click(object sender, EventArgs e)
{
FrmMain frmload = new FrmMain();
utilities.moveBetweenScreens(this, frmload);
}
private void mixtureBtn_Click(object sender, EventArgs e)
{
utilities.loadPopUp(this, mixture);
}
private void FrmProdChoose_Load(object sender, EventArgs e)
{
mixture = new Mixtures(this);
mixtureBtn.Text = selectedDefault;
}
public string Selected
{
get { return selectedDefault; }
set { selectedDefault = value; }
}
}
}
the "pop up"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BakaritCV
{
public partial class Mixtures : MetroFramework.Forms.MetroForm
{
string[] mixture = new string[] { "102", "103", "104", "105" };
MetroFramework.Controls.MetroTile[] tiles;
FrmProdChoose form;
string selectedDefault;
CVFeedUtilities utilities = new CVFeedUtilities();
public Mixtures(FrmProdChoose form)
{
InitializeComponent();
this.form = form;
}
private void btnHome_Click(object sender, EventArgs e)
{
form.Selected = selectedDefault;
utilities.closePopUp(this, form);
}
private void Mixtures_Load(object sender, EventArgs e)
{
tiles = new MetroFramework.Controls.MetroTile[] { tileOne, tileTwo, tileThree, tileFour};
for (int i = 0; i < mixture.Length; i++)
tiles[i].Text = mixture[i];
}
private void tileOne_Click(object sender, EventArgs e)
{
tileOne.BackColor = Color.ForestGreen;
removeBackColor(1);
}
private void tileTwo_Click(object sender, EventArgs e)
{
tileTwo.BackColor = Color.ForestGreen;
removeBackColor(2);
}
private void tileThree_Click(object sender, EventArgs e)
{
tileThree.BackColor = Color.ForestGreen;
removeBackColor(3);
}
private void tileFour_Click(object sender, EventArgs e)
{
tileFour.BackColor = Color.ForestGreen;
removeBackColor(4);
}
private void tileFive_Click(object sender, EventArgs e)
{
tileFive.BackColor = Color.ForestGreen;
removeBackColor(5);
}
public void removeBackColor(int index)
{
for (int i = 0; i < tiles.Length; i++)
{
if (i == index - 1)
{
selectedDefault = tiles[i].Text;
continue;
}
else tiles[i].BackColor = Color.DeepSkyBlue;
}
}
}
}
and the functions loadPopUp and closePopUp
public void loadPopUp(Form from, Form to)
{
to.Tag = from;
to.Show(from);
}
public void closePopUp(Form from, Form to)
{
to.Tag = from;
if (!to.Visible)
to.Show(from);
from.Hide();
}

Turn a repeated foreach loop to a method so that it's only repeated once

So, my issue here may turn out to be simple. I know how to create a method to callback from the application, but my issue is trying to figure out how to do it properly in this manner. I need to take the foreach loop that is repeated :(foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
)
and change it to a method to be called on twice in the code. Please help. Code below.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TicketPurchasing
{
public partial class Form1 : Form
{
private ArrayList events;
public Form1()
{
InitializeComponent();
events = new ArrayList();
}
private void Form1_Load(object sender, EventArgs e)
{
//Create events
events.Add(new Game(12.00, "KSU vs UGA", "Convocation Building", "bball", "Basketball"));
events.Add(new Game(15.00, "KSU vs GSU", "Stadium", "fball", "Football"));
events.Add(new Concert(8.00, "Country Music", "Campus Green", "hayes", "Hunter Hayes"));
events.Add(new Concert(12.00, "Rock/Pop", "Campus Green", "m5", "Maroon5"));
//Load combobox
foreach (Ticket t in events)
{
cbEvents.Items.Add(t.getName());
}
}
private void btnDetails_Click(object sender, EventArgs e)
{
//Get name of selected item from combobox
string eventName;
//Traverse array to determine the match
foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
//Display details
lblDetails.Text = t.getDetails();
//Display image
displayImage(t.getFileName());
}
}
}
private void displayImage(string file)
{
Size size = new Size(173, 180);
Image img = (Image)Properties.Resources.ResourceManager.GetObject(file);
img = (Image)(new Bitmap(img, size));
pbImage.Image = img;
pbImage.Refresh();
pbImage.Visible = true;
}
private void txtTickets_TextChanged(object sender, EventArgs e)
{
//Get number of tickets
int num = int.Parse(txtTickets.Text);
double ticketCost = 0;
//Get cost of ticket
foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
ticketCost = t.getCost();
}
}
//Calculate cost
double total = num * ticketCost;
//Display cost
txtCost.Text = total.ToString("c");
}
private void btnExit_Click(object sender, EventArgs e)
{
//Exit the application
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
//Clear all information
lblDetails.Text = "";
pbImage.Image = null;
txtTickets.Text = "0";
txtCost.Text = "";
}
}
}
Are you trying to achieve something like this?
private void btnDetails_Click(object sender, EventArgs e)
{
//Get name of selected item from combobox
string eventName;
//Traverse array to determine the match
MethodAfterRefactor(() =>
{
//Display details
lblDetails.Text = t.getDetails();
//Display image
displayImage(t.getFileName());
});
}
private void MethodAfterRefactor(Func<object> p)
{
foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
p.Invoke();
}
}
}
Try thinking about this slightly differently, let's start by working out what you really want to do.
You have two lists, one represents the View artefacts cbEvents, the other the data behind that (sometimes known as the ViewModel) events.
What you are trying to do is match your ViewModel from your View because you only put the name into the view.
If you instead put your ViewModel into your View so that it can be rendered as just the name, then this code goes away. Something like
public class Ticket
{
...
public string override ToString() { return getName(); }
}
private void Form1_Load(object sender, EventArgs e)
{
...
//Load combobox
foreach (Ticket t in events)
{
cbEvents.Items.Add(t);
}
}
Then you can do stuff like
private void btnDetails_Click(object sender, EventArgs e)
{
Ticket t = cbEvents.SelectedItem as Ticket;
if (t !=null)
{
//Display details
lblDetails.Text = t.getDetails();
//Display image
displayImage(t.getFileName());
}
}
This is obviously a totally different way of thinking about this but is much easier. You may also find that some controls don't support binding to the object so well, in which case (at least in WinForms) you can use the Tag field
lblText.Text = t.getName();
lblText.Tag = t;
or in WPF the DataContext so you then bind to the fields e.g.
<TextBlock Text="{Binding Name}"/>

send datagridview item to another form

hey i wrote below code to send my datagridview value seleted row to another form but i got this error my event is double content click and i dont know why this happened
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
tblClassTableAdapter.Fill(dataSet1.tblClass);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.tblClassTableAdapter.FillBy1(this.dataSet1.tblClass, textBox1.Text);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
new Form6(int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString())).Show();
}
}
and my form 6
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
public partial class Form6 : Form
{
int classid;
private string p;
public Form6(int myid)
{
classid = myid;
InitializeComponent();
}
public Form6(string p)
{
// TODO: Complete member initialization
this.p = p;
}
public void Form6_Load(object sender, EventArgs e)
{
textBox1.Text = classid.ToString();
}
public DataGridViewRow dataGridViewRow { get; set; }
}
}
thank you guys for helping
DataGridViewCellEventArgs has two important args for you:
e.rowIndex, e.columnIndex which specifying in which cell you pressed.
By the way, you are trying to parse Int from cell, surround it with try/catch for case the parse fails.
try this code instead:
try {
if (e.ColumnIndex > -1 && e.RowIndex > -1)
new Form6(int.Parse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString())).Show();
}
catch (Exception ex) {
MessageBox.Show("Error: " + ex.Message);
}
I think it should help you, mark as answered if yes.

searched items dont be added to list box

items searched in search function: the ALBUMS dont get added to the list box?
the other fields populate
can you please tell me how i can populate the listbox with the searched albums
albums be looked up using a linked list
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment
{
public partial class frmAddArtist : Form
{
AVLTree<Artist> avltree = new AVLTree<Artist>();
LinkedList<Album> temp = new LinkedList<Album>();
Artist artistinst;
Album albuminst;
string noofmembers, artistname;
int artistcount;
public frmAddArtist()
{
InitializeComponent();
}
private void label5_Click(object sender, EventArgs e)
{
}
private void btnAddArtist_Click(object sender, EventArgs e)
{
string tempalbum, date;
tempalbum = txtAlbumName.Text;
date = dtpReleaseDate.Text.ToString();
albuminst = new Album(tempalbum, date);
temp.AddFirst(albuminst);
lbAlbums.Items.Add(tempalbum);
}
private void btnSave_Click(object sender, EventArgs e)
{
artistname = txtArtistName.Text;
noofmembers = txtNoOfMembers.Text;
artistinst = new Artist(artistname, noofmembers, temp);
avltree.InsertItem(artistinst);
artistcount++;
txtArtistName.Clear();
txtNoOfMembers.Clear();
txtAlbumName.Clear();
lbAlbums.Items.Clear();
temp.Clear();
}
private void btnNoOfArtist_Click(object sender, EventArgs e)
{
MessageBox.Show("The No. Artist: " + Convert.ToString(artistcount));
}
private void btnHeight_Click(object sender, EventArgs e)
{
int heightoftree = avltree.Height();
string height = Convert.ToString(heightoftree);
MessageBox.Show("The Height of the Tree: " + height);
}
private void btnSearch_Click(object sender, EventArgs e)
{
Artist temp = new Artist(txtSearch.Text, " ", null);
Artist result = avltree.Search(temp);
if (result != null)
{
if (result.CompareTo(temp) == 0)
{
txtArtistName.Text = result.artistname;
txtNoOfMembers.Text = result.noofmembers;
foreach (Album p in result.Albumslist)
{
lbAlbums.Items.Add(p.Albumname);
}
}
else if(result.CompareTo(temp) <0)
{
MessageBox .Show("No Match Found");
}
}
}
}
}
Put the items into a LinkedList or a List.
Then set lbAlbums.ItemsSource=;

NotImplementedException when searching ListBox

I'm just trying to search strings in my ListBox and I thought I had it pretty much down pat until I came to this issue:
An unhandled exception of type 'System.NotImplementedException' occurred in **.exe
Additional information: The method or operation is not implemented.
Here is my piece of code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace *****
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
search();
}
public void search()
{
if (textBox2.Text == string.Empty)
{
MessageBox.Show("Must enter value");
}
else
{
string toFind = textBox2.Text;
if (toFind != string.Empty)
{
int search = listBox1.FindString(toFind);
if (search != -1)
{
listBox1.SetSelected(search, true);
}
else
{
MessageBox.Show("Could not find "+toFind);
}
}
}
}
public void add()
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Must enter value");
}
else
{
listBox1.Items.Add(textBox1.Text);
}
textBox1.Clear();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
add();
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
search();
}
}
}
}
Search your whole project for following:
throw new NotImplementedException();
and do comment it ;)

Categories

Resources