How to programmatically set IsChecked property on ListboxItem? - c#

I have a listbox, which I fill with a list via ItemsSource = list.
Now, I have another list. And what I want to do is loop through the ListBox, to see if the ListBoxItem.Name is the same. If so, then the ListBoxItem should be selected.
My idea:
List<string> firstList = new List<string>();
List<string> secondList = new List<string>();
Listboxx.ItemsSource = firstList;
foreach (string striing in secondList)
{
foreach (ListBoxItem iitem in Listboxx)
{
if (striing == iitem.Name)
{
iitem.IsSelected = true;
}
}
}
Or is there a way in the ListboxItemTemplate to set the IsChecked bool to {Binding IsCheckedOrNot}?

Nested loops generally should be avoided when possible. Why not do something like this?
foreach(var iitem in Listboxx.Items.Where(i => secondList.Contains(i.Name)))
{
iitem.IsSelected = true;
}

Related

C# can't update ComboBox when Item List is filled

I have a function which clears all Comboboxes on the form and then try to update the text.
The new text is only shown if no Items are in the Item list.
Does anyone have an idea whats wrong?
I deleted all functions from the project so that only the necessary part is available.
https://www.dropbox.com/s/ibst7enrteyk9jb/Digitales_Auftragsformular.zip?dl=0
The project is attached. Simply start, go to tab "Werkzeuganfrage" there are two Comboboxes in red. One without Items = working, one with Items which is not working.
public Oberflaeche()
{
InitializeComponent();
List<ComboBox> myComboBoxes = GetControlsByType<ComboBox>(this, typeof(ComboBox));
foreach (ComboBox txt in myComboBoxes)
{
//txt.Text = "";
txt.SelectedIndex = -1;
}
Werkzeuganfrage_Combobox_rhino1_1.Text = "Rhino1_1";
Werkzeuganfrage_Combobox_rhino1_2.Text = "Rhino1_2";
comboBox1.Text = "Rhino1_1";
comboBox2.Text = "Rhino1_2";
}
public List<T> GetControlsByType<T>(Control container, Type type)
{
List<T> result = new List<T>();
foreach (Control c in container.Controls)
{
if (c.GetType() == type)
{
result.Add((T)Convert.ChangeType(c, typeof(T)));
}
if (c.HasChildren)
{
result.AddRange(GetControlsByType<T>(c, type));
}
}
return result;
}

Retrieving drop down list items from list of controls

I am attempting to retrieve a ListItemCollection from a List of controls. This List contains many controls of different types - DropDownList, Label, TextBox.
I would like to retrieve all ListItem from all the DropDownList controls contained in the original List of controls.
My thought process so far has been to extract all of the DropDownList controls into a new list, and iterate though this to pull out each ListItem - however, every DropDownList control is coming up with 0 items
ControlCollection cList = pnlContent.Controls;
List<DropDownList> ddlList = new List<DropDownList>();
foreach (Control c in cList)
{
if (c.GetType() == new DropDownList().GetType())
{
ddlList.Add((DropDownList)c);
}
}
ListItemCollection itemCollection = new ListItemCollection();
foreach (DropDownList ddl in ddlList)
{
foreach(ListItem li in ddl.Items)
{
itemCollection.Add(li);
}
}
I'm sure this is the wrong (and massively inefficient) way of doing this. Any help would be appreciated.
This will do:
public IEnumerable<ListItem> GetListItems(ControlCollection controls)
{
return controls.OfType<DropDownList>().SelectMany(c => c.Items.OfType<ListItem>());
}
I currently do not have an installation where I can test this, but as a line of thought I would use Linq to do this.
Here is an example that you should be able to use;
var type = new DropDownList().GetType();
var listOfControl = from c in pnlContent.Controls
where c.GetType() == type
select ((DropDownList)c).Items;
Try this:
var ddlList = cList.OfType<DropDownList>();
ListItemCollection itemCollection = new ListItemCollection();
// option 1
var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li).ToArray();
itemCollection.AddRange(temp);
// or option 2
var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li);
foreach (var listItem in temp)
{
itemCollection.Add(listItem);
}
comboBox1.Items.Add(button1);
comboBox1.Items.Add(button2);
comboBox1.Items.Add(dateTimePicker1);
comboBox1.Items.Add(checkBox1);
comboBox2.Items.Add(button3);
comboBox2.Items.Add(button4);
comboBox2.Items.Add(dateTimePicker2);
comboBox2.Items.Add(checkBox2);
comboBox3.Items.Add(button5);
comboBox3.Items.Add(dateTimePicker3);
comboBox3.Items.Add(checkBox3);
comboBox3.Items.Add(checkBox4);
List<ComboBox> ddlList = new List<ComboBox>();
foreach (Control c in panel1.Controls)
{
if (c is ComboBox)
{
ddlList.Add((ComboBox)c);
}
}
List<Control> itemCollection = new List<Control>();
foreach (ComboBox ddl in ddlList)
{
foreach (var li in ddl.Items)
{
itemCollection.Add((Control)li);
}
}

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 find toolstripmenuItem with name

I have set visible property of my menuStrip1 items to false as
foreach (ToolStripMenuItem itm in menuStrip1.Items)
{
itm.Visible = false;
}
Now I know the Names of toolStripMenuItem and dropDownItem of the menustrip1. How to can I activate the required toolStripMenuItem and dropDownItem.
I have
string mnItm = "SalesToolStripMenuItem";
string ddItm = "invoiceToolStripMenuItem";
Now I want to set visible true to these two(toolStripMenuItem and dropDownItem) items. How can I do that? I know those names only.
Simply use those names to get the actual item via MenuStrip.Items indexer:
ToolStripMenuItem menuItem = menuStrip1.Items[mnItm] as ToolStripMenuItem;
ToolStripDropDownMenu ddItem = menuStrip1.Items[ddItm] as ToolStripDropDownMenu;
You can use
menuStrip1.Items[mnItm].Visible = true;
menuStrip1.Items[ddItm].Visible = true;
or if you want to set Visible to multiple toolstrip items:
string [] visibleItems = new [] {"SalesToolStripMenuItem", "invoiceToolStripMenuItem"};
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (visibleItems.Contains(item.Name))
{
item.Visible = false;
}
}
Hope it helps
You're looking for ToolStripItemCollection.Find method.
var items = menustrip.Items.Find("SalesToolStripMenuItem", true);
foreach(var item in items)
{
item.Visible = false;
}
second parameter says whether or not to search the childrens.
You should try something like this:
string strControlVal ="somecontrol"; //"SalesToolStripMenuItem" or "invoiceToolStripMenuItem" in your case
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (strControlVal == item.Name)
{
item.Visible = false;
}
}
Initialize strControlVal string on your discretion where you need it.
If i get your question you are trying to disable other than the above two mentioned toolstrip items. Since you know the name of the menu items a slight change in code can get you along
foreach (ToolStripMenuItem itm in menuStrip1.Items)
{
if(itm.Text !="SalesToolStripMenuItem" || itm.Text !="invoiceToolStripMenuItem")
{
itm.Visible = false;
}
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
string MenuItemName = sender.ToString()
}

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.

Categories