C# multiple select listbox selected item text - c#

I have a list-box, I want to loop through all the selected items and get each selected items text value.
for (int i = 0; i < lstFieldNames.selectedItems.Count; i++)
{
string s = lstFieldNames.SelectedItems[i].ToString();
}
the value of s is "{ Item = ADDR }"
I don't need the { Item = }, I just want the text "ADDR".
What am I doing wrong, I tried a few things and nothing seems to work for me.

Well, this is a Winforms question because an ASP.NET ListBox has no SelectedItems property(notice the plural). This is important since a Winforms ListBox has no ListItems with Text and Value properties like in ASP.NET, instead it's just an Object.
You've also commented that the datasource of the ListBox is an anonymous type. You cannot cast it to a strong typed object later.
So my advice is to create a class with your desired properties:
class ListItem {
public String Item { get; set; }
}
Create instances of it instead of using an anonymous type:
var items = (from i in xDoc.Descendants("ITEM")
orderby i.Value
select new ListItem(){ Item = i.Element("FIELDNAME").Value })
.ToList();
Now this works:
foreach (ListItem i in lstFieldNames.SelectedItems)
{
String item = i.Item;
}
Note that my ListItem class is not the ASP.NET ListItem.

string s = lstFieldNames.SelectedItems[i].Text.ToString();
Note the Text property

This would fetch Selected values only.
EDIT:
foreach (object listItem in listBox1.SelectedItems)
{
string s = listItem.ToString();
}

Use this code :
string s = "";
foreach(var item in lstFieldNames.SelectedItems)
{
s += item.ToString() + ",";
}
textBox1.Text = s;
If need on one selected item from your listbox try this cod :
string s = "";
foreach(var item in lstFieldNames.SelectedItems)
{
s = item.ToString();
}
EDIT :
Try this one code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = "";
foreach (var item in listBox1.SelectedItems)
{
s += item.ToString() + ",";
}
textBox1.Text = s;
}

Related

How to get multiple selected items in asp.net listbox and show in a textbox?

i am trying to add the selected items from the listbox to the textbox with the comma seperated between each other. but it is only reading the first element of the selected items every time.if i select three values holding ctrl its only passing the fist elemnt of selected items
if (ListBox1.SelectedItem != null)
{
// int count = ListBox1.SelectedItems.Count;
if (TextBox1.Text == "")
TextBox1.Text += ListBox1.SelectedItem.ToString();
else
TextBox1.Text += "," + ListBox1.SelectedItem.ToString();
}
if listbox contain :1,2,3,4
example output inside textbox: 1,1,1,1
expected output: 1,2,3,4 (for evry selection it shouldnt display the already selected value again)
var selectedItemText = new List<string>();
foreach (var li in ListBox1.Items)
{
if (li.Selected == true)
{
selectedItemText.Add(li.Text);
}
}
Then
var result = string.Join(selectedItemText,",");
The ListBox has a SelectedItems property, that you can iterate over:
foreach (var item in ListBox1.SelectedItems)
{
TextBox1.Text += "," + item.ToString();
}
At the end you need to remove the first "," as it will be in front of the first items string representation:
TextBox1.Text = TextBox1.Text.Substring(1, TextBox1.Text.Legth - 1);
Try this
var selected = string.Join(",", yourListBox.Items.GetSelectedItems());
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(
this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}

How do i compare a value to a multiple list items in a dropdownlist?

I'm trying to do a logic here where by if an item from db exists in part of the dropdownlist ListItem it will have that item selected, else it will display the new item in a textbox and have the "Others" selected in the dropdownlist.
This is what I have so far
string gameData = readGame["gTitle"].ToString();
string gameTitle = ddlgameTile.Items.ToString();
if (printHouseData == gameTitle)
{
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
}
else
{
txtNewGame.Text = readGame["gTitle"].ToString();
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
}
I tried using Foreach loop and for loop, it still would not work (properly). It only gets the if-else logic by the last ListItem which is the "Others".
Assuming that gameData is the db item you want to select if it does exist, you can use ListItemCollection.FindByValue to get the item or null if it does not exist. Then you can set DropDownList.SelectedValue to select it:
string selectedValue = "Others";
if(ddlgameTile.Items.FindByValue(gameData) != null)
selectedValue = gameData;
ddlgameTile.SelectedValue = selectedValue;
However, if you have set the DataValueField and DataTextField you have to use FindByText.
How about something like this?
var compareTo = new ListItem("Title","Value");
if (ddl.Items.Contains(compareTo))
{
var selectedIndex = ddl.Items.IndexOf(compareTo);
}
else
{
var selectedIndex =
ddl.Items.IndexOf(new ListItem { Value = "Others", Text = "Others" });
}
Assuming I have the context of what you're trying to achieve right, try this:
foreach (string gameTitle in ddlgameTile.Items)
{
if (printHouseData == gameTitle)
{
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue(gameData));
}
else
{
txtNewGame.Text = readGame["gTitle"].ToString();
ddlgameTile.SelectedIndex = ddlgameTile.Items.IndexOf(ddlgameTile.Items.FindByValue("Others"));
}
}

How to traverse the list view column

How to traverse the list view column so that we can check whether item in the list view column already exist or not and if it exist then change the item .
for example i have a list view with (quantity and item) and i want to check if the newly added item already exist in the list view then only change the quantity to quantity ++ rather then adding new item.
string[] saLvwItem = new string[4];
saLvwItem[0] = a.ToString();
saLvwItem[1] = r["ItemNumber"].ToString();
saLvwItem[2] = r["ItemName"].ToString();
saLvwItem[3] = r["Price"].ToString();
ListViewItem lvi = new ListViewItem(saLvwItem);
listView1.Items.Add(lvi);
all the values are coming from database.
If you are trying to match on ItemName (columnIndex=2) and increase the ItemNumber (columnIndex=1), then this may work:
private void InsertOrUpdateItem(ListView listView, string[] saLvwItem)
{
if (saLvwItem == null || saLvwItem.Length < 4)
{
return;
}
bool bFound = false;
foreach (ListViewItem lvi in listView.Items)
{
if (lvi.SubItems[2].Text == saLvwItem[2])
{
// item already in list
// increase the ItemNumber
lvi.SubItems[1].Text = (Convert.ToInt32(lvi.SubItems[1].Text) + Convert.ToInt32(saLvwItem[1])).ToString();
bFound = true;
break;
}
}
if (!bFound)
{
// item not found
// create new item
ListViewItem newItem = new ListViewItem(saLvwItem);
listView.Items.Add(newItem);
}
}
Use following code,
if(!lvi.ContainsKey(saLvwItem[1]))
{
ListViewItem lvi = new ListViewItem(saLvwItem[2]); //Or whatever value you want to show as name
listView1.Items.Add(lvi);
}
Listview has a key-value setting for every item, so you can't set four properties. Your key should be unique and your name should be exactly what you want to display, you can make a name by concatinating 2 or more values.

How do I change the text of a ComboBox item?

I have a combobox filed with the name of dataGridView columns, can I change the text of displayed items in the comboBox to any text I want ?
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
if (dataGridView1.Columns[i].ValueType == typeof(string) &&
i != 6 &&
i != 7 &&
i != 8 &&
i != 9)
comboBox1.Items.Add(dataGridView1.Columns[i].Name);
}
comboBox1.SelectedIndex = 0;
I hope this helps you:
combobox.Items[combobox.FindStringExact("string value")] = "new string value";
The FindStringExact method returns the index of an specific item text, so this can be a better way to change the text of a Combobox item.
Note: This works fine on C#.
If the value you want to use is not suitable as the text in a combobox, I usually do something like this:
public class ComboBoxItem<T> {
public string FriendlyName { get; set; }
public T Value { get; set; }
public ComboBoxItem(string friendlyName, T value) {
FriendlyName = friendlyName;
Value = value;
}
public override string ToString() {
return FriendlyName;
}
};
// ...
List<ComboBoxItem<int>> comboBoxItems = new List<ComboBoxItem<int>>();
for (int i = 0; i < 10; i++) {
comboBoxItems.Add(new ComboBoxItem<int>("Item " + i.ToString(), i));
}
_comboBox.DisplayMember = "FriendlyName";
_comboBox.ValueMember = "Value";
_comboBox.DataSource = comboBoxItems;
_comboBox.SelectionChangeCommitted += (object sender, EventArgs e) => {
Console.WriteLine("Selected Text:" + _comboBox.SelectedText);
Console.WriteLine("Selected Value:" + _comboBox.SelectedValue.ToString());
};
Try this:
ListItem item = comboBox1.Items.FindByText("<Text>");
if (item != null)
{
item.Text = "<New Text>";
}
May be instead of changing the text it would be simple to remove the item from a particular index and insert new item at same index with new text
You can simply change combo box items text by :
my_combo.Items [i_index] = "some string";
The best way you can do that is in this way:
ui->myComboBox->setItemText(index,"your text");

C# CheckBox List Selected Items.Text to Labels.Text

I have a CheckBoxList and 5 labels.
I would like the text value of these Labels to be set to the 5 selections made from the CheckBoxList after the user clicks on a button. How would I get this accomplished?
Thanks in advance.
bind an event to a button,
iterate trough the Items property of the CheckBoxList
set the text value according to the selected property of the listitem
like:
protected void button_Click(object sender, EventArgs e)
{
foreach (ListItem item in theCheckBoxList.Items)
{
item.Text = item.Selected ? "Checked" : "UnChecked";
}
}
to add a value you could do:
foreach (ListItem item in theCheckBoxList.Items)
{
item.Text = item.Selected ? item.Value : "";
}
or display al values in a mini-report:
string test = "you've selected :";
foreach (ListItem item in theCheckBoxList.Items)
{
test += item.Selected ? item.Value + ", " : "";
}
labelResult.Text = test;
find selected items from CheckboxList by Lambda Linq:
var x = chkList.Items.Cast<ListItem>().Where(i => i.Selected);
if (x!=null && x.Count()>0)
{
List<ListItem> lstSelectedItems = x.ToList();
//... Other ...
}
Why don't you have one label and on the button click do something like:
foreach (var li in CheckList1.Items)
{
if(li.Checked)
Label1.Text = li.Value + "<br />";
}
That may not be the exact syntax but something along those lines.
Use this in LINQ:
foreach (var cbx3 in CheckBoxList2.Controls.OfType<CheckBox>().Where(cbx3 => cbx3.ID == s))
{
cbx3.Checked = true;
}

Categories