Return ComboBox From Function? - c#

The below code has a list and loops through each string item in that list and adds it to a ComboBox. This functions correctly, but I am curious if there is a possible way to pass a string list and ComboBox into a function and return the ComboBox with each item in the string list being added.
Example: gets a string list, then adds each string item to the list. This is great if there's one ComboBox; but if there are 3 or more, to avoid code repetition, passing in a list and ComboBox would save code.
List<string> myList = getList();
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}

you can make method like
private void FillCombo(ComboBox myComboBox, List<string> list);
{
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
//alternatively, you can add it like fubo suggested in comment
//myComboBox.Items.AddRange(myList.ToArray());
}
and call it from somewhere in code
List<string> myList = getList();
FillCombo(this.comboBox1, myList);
FillCombo(this.comboBox2, myList);
// etc...

Related

Need to add items to list from checkedlistbox and remove some

There's a checklist that contains strings .
There is a for each loop that checks the checked items and then add those items to the list of strings that's called mylist only if they aren't added already.
What i need is to check for the not checked items in the listbox and remove the strings from mylist after unchecking item from box .
Basicaly i have a list called mylist i need to add whatever checked item from checkedboxlist to mylist and whenever i uncheck an item delete the same string from mylist .
Suggest some solutions. Thanks in advance .
Please, be so kind and review your next question (How to Ask)...
Take advantage of the event anyCheckedListBox.ItemCheck (MSDN):
public class Form1 : Form {
ListBox anyListBox;
CheckedListBox anyCheckedListBox;
public Form1() {
anyListBox = new ListBox();
Controls.Add(anyListBox);
anyCheckedListBox = new CheckedListBox();
anyCheckedListBox.Items.Add("test1");
anyCheckedListBox.Items.Add("test2");
anyCheckedListBox.Items.Add("test3");
anyCheckedListBox.ItemCheck += AnyCheckedListBox_ItemCheck;
Controls.Add(anyCheckedListBox);
}
private void AnyCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.CurrentValue == CheckState.Unchecked)
anyListBox.Items.Add(anyCheckedListBox.Items[e.Index]);
else
anyListBox.Items.Remove(anyCheckedListBox.Items[e.Index]);
}
}
Beware that the strings have to be unique with this quick and dirty solution.
The naïve implementation would be to add a call to List.Remove in your loop if the item is not checked. Assuming the code you have is similar to #AustinFrench's comment, something like:
foreach (var box in checkboxList)
{
if (box.IsChecked && !myList.Contains(box.Text))
{
// if it's checked, add it to the list if it's not already there
myList.Add(box.Text);
}
else if (!box.IsChecked)
{
// if it's not checked, try to remove it from the list
myList.Remove(box.Text);
}
}
Note that you do not need to check whether an item exists before calling List.Remove. It will simply return false if the item does not exist.
Additionally note this is an O(n^2) operation. It is potentially checking the entire contents of myList for each item in your checkboxlist. If the lists are long, you may get better performance by sorting the lists first and making a single simultaneous pass through the pair (or at least sort myList so you can search it more efficiently).
Alternatively, consider completely replacing the contents of myList instead. This requires only a single pass through your checkboxlist:
myList.Clear();
foreach (var box in checkboxList)
{
if (box.IsChecked)
myList.Add(box.Text);
}
Or, using LINQ and taking advantage of List.AddRange:
myList.Clear();
myList.AddRange(checkboxList.Where(box => box.IsChecked).Select(box => box.Text));
The below code has a foreach loop that iterates through a list of CheckBoxes and then checks if each item is checked or not. If not checked then gets the index of that entry from myList and uses RemoveAt method to remove that entry from the list using the index.
foreach (var item in checkboxList)
{
if (!item.IsChecked)
{
int index = myList.IndexOf(item);
if(index != -1)
myList.RemoveAt(index);
}
}

Append clipboard text to a listbox

So I created a variable to hold my clipboard text and I have no idea on how to append it to a listbox.
This is as far as I got..
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.AddRange(items);
}
but that throws me this error..
Argument 1: cannot convert from 'string' to
'System.Collections.Generic.IEnumerable'
What's causing this and how do I fix it? Is this even the correct way of appending text to the listbox?
-UPDATE-
I got this now but everytime I click the button it overwrites the old one instead of appending a new item to the listbox
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.Add(items);
listBox1.DataSource =_items;
How do i append a new item?
Clipboard.GetText has the signature
public static string GetText()
but List<T>.AddRange has the signature
public void AddRange( IEnumerable<T> collection )
So essentially you're trying to add a string as an IEnumerable<T> which gives you the above error.
Better use List<T>.Add for that purpose like that:
_items.Add(items);
your question is about List object and not about ListBox control.
the AddRange() method requires a collection, you can transform your string to a collection (Array) by using Split.
private void clipboardBtn_Click(object sender, EventArgs e)
{
string YourGetClipBoardTextString = "aaa;bbb;ccc;ddd";
List<string> _items = new List<string>();
_items.AddRange(YourGetClipBoardTextString.Split(';').ToArray()); // you can split the string by any char seperator ";" " ", "," etc...
}
if you dont need to split the string just use the Add() method:
_items.Add(YourGetClipBoardTextString);
After your update, you can append new items to a listbox in that manner:
foreach (string itm in _items)
{
listBox1.Items.Add(itm);
}
since you're creating new "_items" on every click, you cannot see the old items. try like this,
List<string> _items = new List<string>();
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
_items.Add(items);
listBox1.DataSource =_items;
}
_items declared outside of method scope.
Your problem is that you are initializing a new list each time:
string items = Clipboard.GetText();
List<string> _items = new List<string>();//<New list here results in removal of existing item
_items.Add(items);
listBox1.DataSource =_items;
Try something like this:
string items = Clipboard.GetText();
List<string> _items = listBox1.DataSource as List<string>;// You may have type casting issues here -
_items.Add(items);
listBox1.DataSource =_items;
First you need to split the clipboard contents into strings for each line, then you need to add them to the list box:
string[] items = Clipboard.GetText().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
listBox1.Items.AddRange(items);
If you don't want to have a separate listBox item for each line, just do this:
listBox1.Items.Add(Clipboard.GetText());

Easy way to get array of selected indexes of CheckBoxList in ASP.NET

Is there a property or a method on the CheckBoxList class that will return an array of ints that represents all of the selected indexes? This is in ASP.NET.
According to the MSDN documentation, there doesn't appear to be. You'll have to iterate the items yourself.
Here is a method that does just that. It iterates each item, checks if it is selected, then adds the index to a list. I use a list because a list is mutable whereas an array is not. Then to return an array, I just call ToArray() on the list.
public int[] selectedIndexesOfCheckBoxList(CheckBoxList chkList)
{
List<int> selectedIndexes = new List<int>();
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
selectedIndexes.Add(chkList.Items.IndexOf(item));
}
}
return selectedIndexes.ToArray();
}
You could create an extension method to simulate the behavior you want. The benefit of that being that you could re-use it on any list control. Below is a rough example (I'm just returning the list of strings of the values, you could return anything though, the index, the value, the entire list item, etc.).
public static List<string> SelectedValues(this ListControl lst)
{
List<string> returnLst = new List<string>();
foreach (ListItem li in lst.Items)
{
if (li.Selected == true)
{
returnLst.Add(li.Value);
}
return returnLst;
}

List for both checkedlist box and combobox

I want to add all selected items of checkedlistbox and combobox to a list and use that list in a for each loop in c#
I tried this
List<String> list=new List<String>();
if (rbtnMultipleScenario.Checked == true)
{
foreach ( CheckedListBox str in clbScenario.SelectedItems)
{
lstitems.Add(str);
}
}
By using String, I am not able to add all the selected items of Checkedlistbox.
Which type of list I have to use?
List<string> list=new List<string>();
if (rbtnMultipleScenario.Checked == true)
{
foreach ( string str in clbScenario.SelectedItems)
{
lstitems.Add(str);
}
}
This assumes that SelectedItems contains a collection of strings (which by your exception it does)

Variable string editing

I have a form on which you can select multiple items to create a code.
Eg. if I clicked on "name", it would add that to the string, then if I clicked "age" it would then add that to the string, but if I unchecked "name", it would remove it from the string.
I have no idea of how to go about this. Can someone help?
Take a List<string> and add/remove items to/from the list. Once you are done, you make a call to string.Join and construct a single string from array.
List<string> items = new List<string>(); // declare globally
private void add(string item)
{
items.Add(item);
}
private void remove(string item)
{
items.Remove(item);
}
private string convertArrayToString(string delimiter, List<string> elements)
{
delimiter = (delimiter == null) ? "" : delimiter;
return string.Join(delimiter, elements.ToArray());
}
Note:
Giving a priority to List<T> over string[] would be a good decision since, here collection would be resize. Have a look at this discussion which can help you on this.
Simply use a List.
List<string> myList = new List<string>();
myList.Add("Somestring");
Then you can use the following methods:
myList.Remove or myList.RemoveAll or myList.RemoveAt and so on.
Why not using List? it allows you to add/remove elements easily?
if you click on name, just add it to the list, when you uncheck the name, remove it from the list,
after that, you can convert your list into a string and use it.
//Add string
var myList = new List<string>();
//After clicking:
myList.add(clickedElement);
//After uncheck
myList.remove(uncheckedElement);
//At the end, just convert your list to string to use it
var myString = string.Join(" ", myList.ToArray());

Categories