I'm developing a small windows store application in C# where I have populated the values and content for a listbox using the following code snippet.
code 1 : adds the song title as a item to a listbox, using the Song class to create the item
private void addTitles(string title, int value)
{
Song songItem = new Song();
songItem.Text = title;
songItem.Value = value;
listbox1.Items.Add(songItem); // adds the 'songItem' as an Item to listbox
}
code 2 : Song class which is used to set values to each item ('songItem')
public class Song
{
public string Text { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Text;
}
}
Population content to the listbox is functioning currently.
What I want is to get the 'Value' of each item on a Click event, on run-time.
For that purpose, how can I read(extract) the Value of the selected Item in the listbox, in C#? ( Value is the songItem.Value )
code 3 : I have tried this code, as trying to figure out a solution, but it didn't work
private void listbox1_tapped(object sender, TappedRoutedEventArgs e)
{
Int selectedItemValue = listbox1.SelectedItem.Value();
}
Therefore it would be really grateful if someone can help me, as I'm an Amateur.
not sure about the "TappedRoutedEventArgs", but I would do
private void listbox1_tapped(object sender, TappedRoutedEventArgs e)
{
var selectedSong = (Song)listbox1.SelectedItem;
if (selectedSong != null) {
var val = selectedSong.Value;
}
}
because SelectedItem is an Object (which doesn't know about the Value property), so you have to cast it to a Song first.
By the way, Value is a property, not a method, so you don't need the parenthesis.
Try like this:
Song song=listbox1.SelectedItem as Song;
or this:
var selected = listbox1.SelectedValue as Song;
Try something like this :
if (listbox1.SelectedRows.Count>0){
Song song=(Song)listbox1.SelectedItem;
int value=song.Value;
}
Related
Apologies if this has been asked already,
I want to know how to declare the datasource of a textbox or a listbox by the currently selected listBox object.
So box 1 has the list of items, and each selection prints to the next box with more information about them (ItemInfo)
Here is my code that I'm working with:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != null)
{
listBox2.DataSource = ItemStorage._?_?_?_?_(listBox1.SelectedItem);
}
}
public class ItemObject
{
public string ItemName { get; set; }
public string ItemInfo { get; set; }
public ItemObject(string itemName, string itemInfo)
{
ItemName = itemName;
ItemInfo = itemInfo;
}
public override string ToString()
{
return ItemName;
}
}
The list name is ItemStorage and the element I want to print to the other box is ItemInfo.
I have found the answer I was looking for:
Instead of using a listBox, I opted for a richTextBox and this is the code I used:
if (listBox1.SelectedIndex != null)
{
try { var Information = ((ItemObject)listBox1.SelectedItem).ItemInfo;
richTextBox2.Text = Information;
}
catch( Exception ex)
{
}
}
This provided me with only getting the information from the selected item I wanted to have, so my listbox has a full total of all the items, while the selection only shows me the information from the one ive selected.
I have a textbox that will be filled by a button click.
When i Click the button, it will compare some values and then copy the value from a dropdownlist it to the first textbox.
But the dropdownlist only copies the first value, even if i select a second or third value, it will always copy the first.
Here is my code:
protected void BtnOrderKoppelen_Click(object sender, EventArgs e)
{
if(DDLLijnRequest.Text == "Lijn1")
{
TbProd5.Text = DDLVrijgeefOrder.Text;
}
else if (DDLLijnRequest.Text == "Lijn2")
{
TbProd6.Text = DDLVrijgeefOrder.Text;
}
else if (DDLLijnRequest.Text == "Lijn3")
{
TbProd7.Text = DDLVrijgeefOrder.Text;
}
else if (DDLLijnRequest.Text == "Lijn4")
{
TbProd8.Text = DDLVrijgeefOrder.Text;
}
}
DDLLijnRequest= a dropdownlist for my production line comparison
TbProd(5 till 8) = are textboxes where data from DDLVrijgeefOrder has to go to
DDLVrijgeefOrder = a dropdownlist where i select an order and want it to copy to the textboxes.
Is there a way that it could copy any value that i have selected in DDLVrijgeefOrder?
This is my pageload, it has no connection yet with the button click or the dropdownlist. Do i have to add something here? :
protected void Page_Load(object sender, EventArgs e)
{
if (Session["MesLogin"] == null)
{
Response.Redirect("StartPagina.aspx");
}
else
{
LblSession.Text = "Welcome" + Session["MesLogin"].ToString();
}
}
Thank you in advance!
Hope you bind the drop-down value all the time in Page_load event. Drop down data source should be binded only in very first time otherwise it will always bind to first value.
Example:
Void Page_Load()
{
if(!IsNotPostBack)
{
// bind drop down values here
}
}
If the above solution doesn't help, please post some more code like Page_Load event
Based on the context of your question you are using WinForms right?
The following link provides a good answer to your question:
How to create a drop down menu in WinForms and C#
Note that you can add any type of item to the ComboBox. If you don't
specify the DisplayMember and ValueMember properties, the ComboBox
uses the ToString method of the object in order to determine the text
displayed and you can retrieve the selected item (not selected value)
through the SelectedItem property.
class Person
{
public int PersonID { get; set }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return FirstName + " " + LastName;
}
}
Eventually you can do
Person selectedPerson = (Person)myComboBox.SelectedItem;
int personID = selectedPerson.PersonID;
I am trying to set up a multi-language application, so when the user changes the display language all the texts in all the open windows change automatically.
I am having issues through with binding combo-box control. The binding needs to be done in code-behind as I have dynamic content coming from a database, and sometimes I even have to create additional combo-boxes at runtime.
Also I do not want to keep the translations in the database because I do not want to query the database every time a user is changing the display language.
What I did until now:
in xaml:
<ComboBox x:Name="cmb"/>
and in C#:
public class MyCmbItem
{
public int Index { get; set; }
public string Text { get; set; }
}
private ObservableCollection<MyCmbItem> LoadText()
{
ObservableCollection<MyCmbItem> _result = new ObservableCollection<MyCmbItem>();
foreach (var _item in _list)
{
//the list is coming from a database read
_result.Add(new MyCmbItem { Index = _item.Value, Text = _res_man_global.GetString(_item.KeyText, _culture) });
}
return _result;
}
public ObservableCollection<MyCmbItem> MyTexts
{
get { return LoadText(); }
set {} //I do not have to add/remove items at runtime so for now I leave this empty
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
...
LoadList(); //this adds values in _list
cmb.ItemsSource = MyTexts; //this populates the combo-box
Here I got stuck and I do not know how to determine the combo-box to refresh the displayed texts. The method must achieve that if I have several windows opened each containing a random number of combo-boxes, when I change the current language all the combo-boxes in all the windows will refresh the displayed list, without affecting other values inside (like the selected item). Does anybody know how this can be done?
Many thanks.
For your xaml UI, the INotifyPropertyChanged interface indicates updates of the viewmodel. You can extend your class like this:
public class MyCmbItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string APropertyName)
{
var property_changed = PropertyChanged;
if (property_changed != null)
{
property_changed(this, new PropertyChangedEventArgs(APropertyName));
}
}
private string _Text;
private string _KeyText;
public int Index { get; set; }
public string Text
{
get { return _Text;}
set {
if (_Text != value)
{
_Text = value;
NotifyPropertyChanged("Text");
}
}
}
public MyCmbItem(string key_text, int index)
{
Index = index;
_KeyText = key_text;
RefreshText();
_res_man_global.LanguageChanged += () => RefreshText();
}
public void RefreshText()
{
Text = _res_man_global.GetString(_KeyText, _culture);
}
}
Your view can simply bind to the Text-property as following:
<DataTemplate DataType="{x:Type local:MyCmbItem}">
<TextBlock Text="{Binding Path=Text}"/>
</DataTemplate>
Note: I assumed that your language class is global and has some kind of language-changed notification event.
I've got a listbox in C# that's dynamically filled. I've got a problem with the selectedindex_changed of the listbox. Everytime it gives the value of the last item in the listbox and not the one I selected. I've got that same problem with a combobox on another page.
I don't know why this happens this way. Does anyone knows what I'm doing wrong?
First I make a new object Item to put text with the ID as the value in the listbox.
public class Item
{
public string Text { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Text;
}
}
Here I fill the listbox with the text and the ID as its value. This works fine, the listbox gets filled as it should be.
private void FormDeelnemers_Load(object sender, EventArgs e)
{
BLPersoon blPersoon = new BLPersoon();
DBOpdracht.PersoonDataTable personen = blPersoon.GetAllPersonen();
//Item item = new Item(); -> edit: delete this
foreach (DBOpdracht.PersoonRow persoon in personen)
{
Item item = new Item(); -> edit: add this here
item.Text = persoon.naam;
item.Value = persoon.ID;
listBoxPersonen.Items.Add(item);
}
}
Here is the problem. It gives the value of the last item in the listbox and not the one I've selected. How do I get the selected one?
private void listBoxPersonen_SelectedIndexChanged(object sender, EventArgs e)
{
int nummer = (listBoxPersonen.SelectedItem as Item).Value;
MessageBox.Show(nummer.ToString());
//MessageBox.Show(listBoxPersonen.SelectedItem.ToString()); -> same problem
}
Thanks to #bmused who solved it in the comments, but could anyone explain what happened exactly?
i had the same problem with a combobox where i was adding items using a foreach. the question is what does the instantiation of an item during the insertion have to do with selecting from a combobox?
P.S. Sorry admins couldn't post this as comment.
I can't understand the following 2 issues given this code. I mapped a combobox to a custom object and I want each time that the selected value change on the combobox, the custom object changes too.
public partial class MainForm : Form
{
private Person _person;
public MainForm()
{
InitializeComponent();
_person = new Person();
//Populating the combox, we have this.comboBoxCities.DataSource = this.cityBindingSource;
cityBindingSource.Add(new City("London"));
cityBindingSource.Add(new City("Paris"));
_person.BirthCity = new City("Roma");
cityBindingSource.Add(_person.BirthCity);
cityBindingSource.Add(new City("Madrid"));
//Doing the binding
comboBoxCities.DataBindings.Add("SelectedItem", _person, "BirthCity");
}
private void buttonDisplay_Click(object sender, EventArgs e)
{
MessageBox.Show("BirthCity=" + _person.BirthCity.Name);
}
private int i = 0;
private void buttonAddCity_Click(object sender, EventArgs e)
{
City city = new City("City n°" + i++);
cityBindingSource.Add(city);
comboBoxCities.SelectedItem = city;
}
}
public class Person
{
private City _birthCity;
public City BirthCity
{
get { return _birthCity; }
set
{
Console.WriteLine("Setting birthcity : " + value.Name);
_birthCity = value;
}
}
}
public class City
{
public string Name { get; set; }
public City(string name) { Name = name; }
public override string ToString() { return Name; }
}
1 - why when I manually select twice in a row (or more) different value on the combobox, I got only one call to BirthCity.Set witht he last selected value (and the call seems firing only when the combobox lost the focus) ?
2 - why when I click buttonAddCity and then buttonDisplay, the diplayed city is not the one selected (not the one displayed in the comobox )
why when I manually select twice in a row (or more) different value on the combobox, I got only one call to BirthCity.Set witht he last selected value (and the call seems firing only when the combobox lost the focus) ?
That's how Data Binding works, data is moved from the control to the property when validation occurs, and validation occurs when the control loses focus.
why when I click buttonAddCity and then buttonDisplay, the diplayed city is not the one selected (not the one displayed in the comobox )
I don't know. I created a simple form (Visual C# Express 2008 using .Net 3.5 SP1) and pasted your code pretty much verbatim, and it works as expected: it shows the new city in the combo box.
If you add comboBoxCities.Focus (); to the end of buttonAddCity_Click (), you'll make sure the new city gets pushed into _person.BirthCity earlier rather than on ValidateChildren ().