Casting to get ID from selected doesn't work - c#

I try to get a category-id from the selected item in the dropdownlist. I fill the dropdownlist with a foreach loop (using a list).
This is the code that I am using to get the ID:
protected void dropDownCategories_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
Category category = (Category)ddl.Items[ddl.SelectedIndex];
int CatID = category.CategoryID;
}
The code above doesn't work, and gives me this error:
Error 2 Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'XXXXXX.classes.Category'
But when I use the similar code for a listbox, the code below works!
protected void listBoxCategories_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
Category category = (Category)lb.Items[lb.SelectedIndex];
int CatID = category.CategoryID;
}
Why does this piece of code work for a listbox and not for a dropdownlist?
Thanks!

System.Web.UI.WebControls.DropDownList has a ListItemCollection as its Items property, which is a list of ListItem, an object that has a text and a value properties.
while
System.Windows.Forms.ListBox has an ObjectCollection as its Items Property, which is basically a list of objects
so when you add an item to a drop down list you are adding a List Item, which can't be converted to your type, i will need to see your drop down list filling code to know what you are storing in each item.
however when you add an item to a list box, you are adding a object, so if in each item you add an instance of your class then it can be converted back by casting.

Related

Get ListView Item Values of row tapped

Get ListView Item Values of row tapped. I am able to get the item tapped in code behind like so:
private async void Item_Tapped(object sender, ItemTappedEventArgs e)
{
ListView listView = (ListView)sender;
if (listView != null)
{
string pName = e.Item //.PNname; **<<-- This is returning my bound values (4 items) as PName, PNumber... and so on**
}
}
I try to type the .PName it is a sub value to the e.Item list but that is invalid. I really need to grab by name because it appears the return selected row item returns values in a random way? One time PName will be first then next it might be 2nd or 3rd?
Anyway what am I missing to grab the values I need?
I'm doing a lot more visual things here but wanted to keep this code very simple to what I am actually having an issue with getting the individual values in the row.
TIA!
Cheers!
Rick...
e.Item is an object (datatype), if I am not mistaken. You have to cast e.Item to the right data type first:
string pName = (e.Item as Person)?.PName;
(assuming that PName is a property of the class Person)
Try get the itemIndex clicked and get the element in the list or use the AutomationId.

Refer List entrys to a ComboBoxItem

Situation: I have 3 TextBoxes, a button and a ComboBox. When I enter something in every TextBox and trigger the button, I want that the strings I've written in the TextBoxes can be choosen in the ComboBox as a ComboBoxItem. I've got the idea of putting the strings from the TextBoxes into a list and refer the ComboBoxItem to the correct list-entrys. Or is there a more efficient way to set and get these strings?
Would be nice if some could help me writing the code for it.
private void bAdd_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
int txBetrag;
txBetrag = int.Parse(betrag1.Text);
int txMonate;
txMonate = int.Parse(monate1.Text);
int txZins;
txZins = int.Parse(zins1.Text);
List<int> abList = new List<int>();
comboBox.Items.Add("1");
}
If you simply want to add txBetrag, txMonate and txZins to your combobox then you don't need a list. At the moment you're creating a list, adding nothing to it and then simply adding 1 entry to your comboBox (not even from your list).
To add your items just do:
comboBox.Items.Add(int.Parse(betrag1.Text));
comboBox.Items.Add(int.Parse(monate1.Text));
comboBox.Items.Add(int.Parse(zins1.Text));
If you really need the list as well (perhaps because it is used elsewhere as well) then you can do the following:
abList.Add(int.Parse(betrag1.Text));
abList.Add(int.Parse(monate1.Text));
abList.Add(int.Parse(zins1.Text));
Then use the list to populate the comboBox:
foreach(var item in abList)
{
comboBox.Items.Add(item);
}
UPDATE
Based off your comment it seems like you want ONE entry in the comboBox that is effectively the 3 textbox values concatenated together. So you could do something like this:
comboBox.Items.Add(betrag1.Text + monate1.Text + zins1.Text);
UPDATE 2
Following you're last comment regarding the fact that you want 1 comboBox item that refers to the 3 values, but doesn't display them, yes you can do this.
Assuming you won't have duplicate entries in the comboBox you could use a Dictionary to map your values to an entry rather than use a list. I'm assuming here that you will have more than 1 entry in your comboBox eventually, otherwise it's a bit pointless having a combobox.
var valueComboMapping = new Dictionary<string, int[]>();
valueComboMapping.Add("Entry 1", new int[] {int.Parse(betrag1.Text), int.Parse(monate1.Text), int.Parse(zins1.Text)};
This will enable you to add mappings at a later date. You can then use the Dictionary to create the listings in the comboBox like this:
foreach(var entry in valueComboMapping.Keys)
{
comboBox.Items.Add(entry);
}
To trigger an event off selecting an item in the comboBox using the SelectedIndexChanged event.
Retrieving the Values
To retrieve your mapped values in the SelectedIndexChanged event you can do something like:
private void comboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
ComboBox comboBox = (ComboBox) sender;
string entryName = (string) comboBox.SelectedItem;
//retrieve the values from the dictionary using the value of 'entryName'.
List values = new List<int>();
if (valueComboMapping.TryGetValue(entryName, out values)
{
//do something if the key is found.
}
else
{
//do something else if the key isn't found in the dictionary.
}
}
To get this to work you would need to create the dictionary as follows:
var valueComboMapping = Dictionary<string, List<int>>();
Instead of:
var valueComboMapping = Dictionary<string, int[]>();
You can add directly to combobox,no need to add to list.You are using int.Parse, it will generate Format exception.
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(betrag1.Text);
comboBox1.Items.Add(monate1.Text);
comboBox1.Items.Add(zins1.Text);
}

How to get listbox selected item value

I am working with C# .NET 4.0
I am trying to get the value of a single selected item in a listbox.
This is how I populate the control:
this.files_lb.DataSource = DataTable object
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
But all it returns is "System.Data.DataRowView".
At this link : Getting value of selected item in list box as string
someone suggested -
String SelectedItem = listBox1.SelectedItem.Value
However, 'Value' is not an option when I try this.
How can I get the ValueMember value from a single selected item in a listbox?
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.
It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:
private void button1_Click(object sender, EventArgs e)
{
string selected = listBox1.GetItemText(listBox1.SelectedValue);
MessageBox.Show(selected);
}
And the result:
Edit
It looks like your issue may be from not setting a property on the control:
Select the ListBox control
Click the little arrow to show the binding / items options
Select Use Data Bound Items
If I deselect that box, I get the exact same behavior you are describing.
var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{
MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}
You may need to set the DataValueField of the listbox.
NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
NewEmployeesLB.DataTextField = "Text";
NewEmployeesLB.DataValueField = "Value";
NewEmployeesLB.DataBind();

Getting multiple values from a List box in C# windows form

I have a list box that is pulling it's data from a sql table. I have its selection mode set to multisimple.
I have the display member for each item set to the Name field from the sql table and the value member for each item set to the ID field from the sql table.
When I select multiple items from the list, how do I get the multiple values? I am able to get the text of one item by using the listboxname.Text but I don't know how to get each value that has been selected all at once.
Any help will be greatly appreciated.
Use the SelectedItems property, the following will get a List<string> representing the selected items:
var items = listBox1.SelectedItems.Cast<object>()
.Select(x=>Convert.ToString(x)).ToList();
To get the exact values (ID), it depends on the underlying item type. If you use a DataTable as DataSource for your listBox, the underlying item type is DataRowView, so the code to get the values IDs should be:
var ids = listBox1.SelectedItems.Cast<DataRowView>()
.Select(row=>row.Row.Field<string>("ID")).ToList();
//suppose the ID field is string
If the underlying item type is just a normal class with 2 properties Name and ID, such as call it Item, the code is simpler like this:
var ids = listBox1.SelectedItems.Cast<Item>()
.Select(item=>item.ID).ToList();
Method 1 : You can use SelectedIndices property of the ListBox to get the All selected items Index values.
then for each selected index you can get the Value of the Item.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (int i in listBox1.SelectedIndices)
{
SelectedItems.Add(listBox1.Items[i].ToString());
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox
Method 2:
You can use SelectedItems property of the ListBox to get the All selected item values directly.
Try This:
private void button1_Click(object sender, EventArgs e)
{
List<String> SelectedItems=new List<String>();
foreach (String s in listBox1.SelectedItems)
{
SelectedItems.Add(s);
}
}
Note : List SelectedItems contains all SelectedItems from the ListBox

How to Get id key from List View - C# Windows application

I am listing set of table items(only names) in List View. I enabled checkbox property of ListView. I displayed all items as Large icons. I want to attach a key(id) for that items for further processing on that items.. If any idea , please reply
Use the ListViewItem.Name property. Poorly named, it is actually the key. The one you can pass to ListView.Items.IndexOfKey() or ListView.Items["key"].
Description
You should use the Tag property for things like that.
Gets or sets the object that contains data about the control.
You can set your id or any other object to the ListItem you want.
Sample
Add the Item
ListViewItem myItem = new ListViewItem();
myItem.Tag = 1; // or any other object
listView1.Items.Add(myItem);
Use the index
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
ListViewItem myItem = e.Item;
int index = (int) myItem.Tag; // cast to your object type, int in this case
// use the index
}
More Information
MSDN - Control.Tag Property

Categories