I want to bind my arraylist to dropdown menu list. Here is my code.
I'm a beginner to C#. Please help.
if (selectinidialog.ShowDialog() == DialogResult.OK)
{
selectinibtn.Text = selectinidialog.FileName;
IniFile inifile = new IniFile(selectinidialog.FileName);
string[] sectorelist = inifile.GetSectionNames();
var sectorno = new List<string[]>;
sectorno.Sort();
selectsectorbtn.DataSource = sectorno;
selectsectorbtn.DataBind();
}
It looks like you're getting the data you want:
string[] sectorelist = inifile.GetSectionNames();
But then you don't do anything with that data. (You never use the sectorelist variable again.) Instead, you create a new empty list and bind to that:
var sectorno = new List<string[]>;
sectorno.Sort();
selectsectorbtn.DataSource = sectorno;
selectsectorbtn.DataBind();
Are you just looking to bind to the data you first got from inifile?:
string[] sectorelist = inifile.GetSectionNames();
selectsectorbtn.DataSource = sectorelist;
selectsectorbtn.DataBind();
It's worth a try. Though it's not entirely clear what you're specifically trying to do because you're working with two very different types here. You fetch a string[] but then you try to bind to a List<string[]>. If you need to bind to the latter for some reason then you'd need to translate the former to that somehow (based on whatever logic you'd use to define that translation). But if that was just a typo or other simple mistake, then it sounds like you can just bind to the data and don't need that List<string[]> at all.
I would suggest but dont take my answer for the best 1 that you rather not directly bind the list with an array.
rather loop through it and add one item at a time or use the AddRange() functionality in the right conditions.
Example :
if (selectinidialog.ShowDialog() == DialogResult.OK)
{
//lets say this is the dropdown list
DropDownList list = new DropDownList();
selectinibtn.Text = selectinidialog.FileName;
IniFile inifile = new IniFile(selectinidialog.FileName);
string[] sectorelist = inifile.GetSectionNames();
list.Items.Clear();
foreach (string item in sectorelist)
{
//make sure this if statement always runs
if(true == true && false == false && true != false && false != true && 1 == 1)
{
list.Items.Add(new ListItem() { Text = item });
}
}
}
Related
I am populating a listBox at runtime from a database as follows:
List<FILE_REPORT_TYPES> ReportTypes = GetReportTypesFromDatabase(ReportMappingIds)
BindingList<FILE_REPORT_TYPES> pbReportTypesBindingList = new BindingList<FILE_REPORT_TYPES>(ReportTypes);
listBoxReports.DataSource = ReportTypesBindingList;
listBoxReports.DisplayMember = "REPORT_DESCRIPTION";
listBoxReports.ValueMember = "REPORT_ID";
I then would like select multiple items on the listBox when running the windows form and retrieve each individual Value of my selections. If only one selection is made one could do the following:
listBoxReports.SelectedValue;
I would like to do the following:
var list = listBoxReports.SelectedValues;
However this is not allowed i.e. "SelectedValues" does not exist.
Some people are erroneously suggesting that in this particular case SelectedIndices may be used. It cannot be used, I am trying to retrieve the "VALUE". This cannot be done (in this particular case):
listBox.Items[i].Value;
I think the solution should be along the lines of:
foreach(var line in listBox.Items)
{
var res= ((SOME CASTING)line).Value;
}
To get the selected items you have 2 options
a.) ListBox.SelectedIndices which returns the indices of the selected items which you then need to use to look up in the Items property what the value is or
b.) ListBox.SelectedItems which returns you a collection with the selected items themselves (be aware that it is an objectlist so you need to transform the items into your appropriate datatype).
Edit: With the additional information the following is possible
List<FILE_REPORT_TYPES> mySelectedList = new List<FILE_REPORT_TYPES>();
foreach (Object selectedItem in ListBox.SelectedItems)
{
mySelectedList.Add( ((FILE_REPORT_TYPES)selectedItem) );
}
You can use ListBox.SelectedIndices or ListBox.SelectedItems.
If you want to get all selected-items, you can let the foreach cast:
foreach(FILE_REPORT_TYPES frt in listBox.SelectedItems)
{
// ...
}
or if you want to get the ReportID into a list with the help of LINQ:
List<decimal> reportIds = listBox.SelectedItems.Cast<FILE_REPORT_TYPES>()
.Select(frt => frt.REPORT_ID)
.ToList();
Alternative to the selected value you could do the following
listBoxReports.SelectedItems;
Answer (the casting is the trick):
List<decimal> reportIds = new List<decimal>();
foreach(var line in listBoxReports.SelectedItems)
{
reportIds.Add(((PB_FILE_REPORT_TYPES)line).REPORT_ID);
}
You may try like below
List<FILE_REPORT_TYPES> reportList = new List<FILE_REPORT_TYPES>();
foreach(var item in listBox.SelectedItems)
{
reportList.Add((FILE_REPORT_TYPES)item);
}
In WPF there's no listbox.findString.
Let's say we have a listbox:
ListBox b = new ListBox();
Then you could use LINQ:
int index = b.Items.IndexOf((
from ListBoxItem a in b.Items
where a.Content.ToString() == "something"
select a).First());
Or you can use foreach:
foreach (ListBoxItem lbi in b.Items)
{
if (lbi.Content is string && (string)lbi.Content == "something")
{
index = b.Items.IndexOf(lbi);
break;
}
}
var entries = listBox.Items.Where(item => item.ToString() == "something");
In most scenarios, you want to bind the ListBox's ItemsSource to an actual collection in your code that implements IEnumerable, then use the .Where().First() statement to find the first occurence of your string, like this:
List<string> lstb = new List<string>() { "StringA", "StringB", "StringC" };
string stringC = lstb.Where(s => s == "StringC").First();
Then if you want to programmatically select the item in your list:
yourListBox.SelectedItem = stringC;
However I strongly suggest you take the time to learn about databinding and the MVVM model which simplifies interaction with WPF controls by a lot.
I am using a multi-selection ListPicker (the new one in the 7.1/Mango control toolkit from Nov '11).
My code is below - a "vanilla" use case for the ListPicker, except that I initialize the SelecetedItems dependency property with a new List so I can add things to it and properly initialize the selected state for the ListPicker. Although this issue repro's whether or not I do this...
The SummaryForSelectedItemsDelegate does get called when initializing the list (e.g. when I call contactPicker.SetValue(ListPicker.SelectedItemsProperty)), but NOT when I click the "done" button on the ListPicker (although my SelectionChanged event handler does get called).
Once I dismiss the ListPicker, I only get the string corresponding to the first selected item in the "summary" for the control (as opposed to the control calling my delegate and getting a comma-delimited list of selected items).
Is this a bug? Has anyone else run into this? Is there a workaround?
var contactPicker = new ListPicker()
{
MinWidth = minWidth,
ExpansionMode = ExpansionMode.FullScreenOnly,
SelectionMode = SelectionMode.Multiple,
SummaryForSelectedItemsDelegate = (list) => { return CreateCommaDelimitedList(list); },
IsTabStop = true
};
contactPicker.ItemsSource = listOfItems;
contactPicker.DisplayMemberPath = "Name";
contactPicker.SetValue(ListPicker.SelectedItemsProperty, new List<Item>());
// initialize the list picker selected values
foreach (var contactRef in listOfSelectedContacts)
contactPicker.SelectedItems.Add(contactRef);
contactPicker.SelectionChanged += new SelectionChangedEventHandler((o, ea) =>
{
// add all the newly added items
foreach (var added in ea.AddedItems)
{
Item addedItem = added as Item;
if (addedItem == null)
continue;
listOfSelectedContacts.Items.Add(addedItem);
}
// remove all the newly removed items
foreach (var removed in ea.RemovedItems)
{
Item removedItem = removed as Item;
if (removedItem == null)
continue;
listOfSelectedContacts.Items.Remove(removedItem);
}
});
I should have posted my my summary delegate... which is actually where my bug was :-(
Even though I was creating the SelectedItems as a List, and each of the elements in the IList passed in are typed "Item", the concrete type of the IList passed in is NOT List. Therefore the null check succeeds and the method returns null. And of course my breakpoint was right after that line so it looked like the method wasn't getting invoked. Duh.
private string CreateCommaDelimitedList(IList ilist)
{
IList<Item> list = ilist as IList<Item>;
if (list == null)
return null;
// build a comma-delimited list of names to display in a control
List<string> names = list.Select(it => it.Name).ToList();
StringBuilder sb = new StringBuilder();
bool comma = false;
foreach (var name in names)
{
if (comma)
sb.Append(", ");
else
comma = true;
sb.Append(name);
}
return sb.ToString();
}
I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.
I am trying to get a list of all elements from ListBox if no or one of items is selected or list of selected items if more than 1 are selected. I have written such a code but it doesn't compile :
ListBox.ObjectCollection listBoXElemetsCollection;
//loading of all/selected XMLs to the XPathDocList
if (listBoxXmlFilesReference.SelectedIndices.Count < 2)
{
listBoXElemetsCollection = new ListBox.ObjectCollection(listBoxXmlFilesReference);
}
else
{
listBoXElemetsCollection = new ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
}
So for this piece of code to work I would need to use something like ListBox.SelectedObjectCollection listBoxSelectedElementsCollection; which I do not want because I would like to use it in such an foreach:
foreach (string fileName in listBoXElemetsCollection)
{
//...
}
I'd simply this a bit and not mess with the ListBox ObjectCollections if you don't need to. Since you want to iterate items on your ListBox as strings, why not use a List and load the list how you show:
List<string> listItems;
if (listBoxXmlFilesReference.SelectedIndices.Count < 2) {
listItems = listBoxXmlFilesReference.Items.Cast<string>().ToList();
} else {
listItems = listBoxXmlFilesReference.SelectedItems.Cast<string>().ToList();
}
foreach (string filename in listItems) {
// ..
}
You need to convert SelectedObjectCollection to an array of object[].
ListBox.SelectedObjectCollection sel = new
ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
ListBox.ObjectCollection col = new
ListBox.ObjectCollection(listBoxXmlFilesReference,
sel.OfType<object>().ToArray());
I can see what you're trying to do and it doesnt compile because the type ListBox.ObjectCollection is not the same as ListBox.SelectedObjectCollection - even though in your case they are lists that contain strings the classes themselves are different hence the compile error.
Assuming your items are strings in the listbox you could do:
var items = listBoXElemetsCollection.Items.OfType<string>();
if (listBoXElemetsCollection .SelectedIndices.Count >= 2)
items = listBoXElemetsCollection.SelectedItems.OfType<string>();
foreach(var item in items)
//do stuff