public Core()
{
InitializeComponent();
Archive.IntializeObjects();
Data.Load();
adultBox.DataSource = display;
}
void UpdateUI()
{
display.Clear();
foreach (Lesson l in lessons)
{
display.Add(l);
}
MessageBox.Show(lessons.Count.ToString());
adultBox.DisplayMember = "Title";
}
This method updates a separate list to filter from a larger list and then post it to a ListBox. Though the lessons list updates properly and contains multiple objects, only one item is ever shown in the box.
What am I missing?
Use this:
display.Items.Add(l);
or
display.Items.AddRange(l.ToArray());
Related
I have 2 forms: 1 form contains a listView and another form contains a comboBox.
I would like the first column of the listView to be loaded into the comboBox on the second form.
This is my attempt:
comboBox1.Items.Add(Form2.listView2.columnHeader1);
However, this does not work. (Form2.ListView is inaccessible due to its protection level). Suggestions would be appreciated.
Quick and dirty solution:
Go to the Properties of listView2 in the winforms designer and look for Modifiers. Then select Public like you see in the picture below:
And now it will be accessible
The more elegant solution:
Create a property in your first Form which has only a getter. In this getter you can safely return the columnHeader1:
public ColumnHeader ColumnHeader { get { return this.listView1.Columns["columnHeader1"]; }}
or:
public ColumnHeader ColumnHeader { get { return this.columnHeader1; }}
EDIT:
It seems that you rather would like to have all values from that column. So in this case you would have to return all the values, which can be done like this:
public List<string> AlllValuesFromColumn
{
get
{
int indexOfColumn = listView2.Columns.IndexOf(this.columnHeader1);
return listView2.Items.OfType<ListViewItem>().Select(x => x.SubItems[indexOfColumn].Text).ToList();
}
}
To Add all the values in one blow to the ComboBox you can use AddRange:
comboBox1.Items.AddRange(Form2.AlllValuesFromColumn.ToArray());
EDIT 2:
But the solution I personally would prefer is to hold the data source in an extra variable. This can be passed around. No magic there.
Make a public method in your second form and let the method set the comboboxitems.
Form1:
bool Do = true;
int i = 0;
Form2 F = new Form2();
while (Do)
{
try
{
F.AddItem(listView1.Columns[i].Name);
i++;
}
catch
{
Do = false;
}
}
Form2:
public void AddItem(string ToAdd)
{
comboBox1.Items.Add(ToAdd);
}
I'm working on a windows phone project. I have a listbox with the following selectionchanged event handler:
private void judgeType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadJudgeCategories(judgeTypeListBox.SelectedItem.ToString());
}
Here is the LoadJudgeCategories method:
void LoadJudgeCategories(string judgeType)
{
string[] categories = judgeCategories[judgeType];
List<LabeledTextBox> itemSource = new List<LabeledTextBox>();
foreach (string cat in categories)
{
itemSource.Add(new LabeledTextBox(cat));
}
CategoryPanel.ItemsSource = itemSource;
}
judgeCategories is of type
Dictionary<string, string[]>
LabeledTextBox is usercontrol with a textblock and a textbox. CategoryPanel is just a listbox.
Whenever the selected item is changed, I want to clear CategoryPanel, and replace it with a new List.
Occasionally, however, when I change the selection, it gives the exception "value does not fall within the expected range".
How do I fix this?
This can happen when you add multiple controls with the same name. Try this code. Broken down with newlines for clarity. I turned it into a linq statement, and also named each of the LabeledTextBox something random.
Note: the only important thing I did was give the LabeledTextBox a name.
Random r = new Random();
void LoadJudgeCategories(string judgeType)
{
CategoryPanel.ItemsSource =
judgeCategories[judgeType]
.Select(cat =>
new LabeledTextBox(cat) { Name = r.Next().ToString() }
).ToList();
}
Just an alternative solution with ObservableCollection - there will be no need to set CategoryPanel.ItemsSource multiple times:
private ObservableCollection<LabeledTextBox> itemSource = new ObservableCollection<LabeledTextBox>();
CategoryPanel.ItemsSource = itemSource; // somewhere in the Constructor
void LoadJudgeCategories(string judgeType)
{
itemSource.Clear();
foreach (string cat in judgeCategories[judgeType])
itemSource.Add(new LabeledTextBox(cat));
}
I have searched around but could not find any references.
How do I delete an item in a generic list that relates to items in a listbox?
I currently have a public static List<Employees> and a listbox named lstRecords, I can remove the item in the listbox just fine, but either everything is removed from the list or nothing at all.
This was my first set of code I was working with:
private void DeleteRecord()
{
if (lstRecords.Items.Count > 0)
{
for (int i = 0; i < lstRecords.Items.Count; i++)
{
if (lstRecords.GetSelected(i) == true)
{
Employees employeeRecord = lstRecords.SelectedItem as Employees;
employee.Remove(employeeRecord);
}
}
lstRecords.Items.Remove(lstRecords.SelectedItem);
}
}
}
This is my 2nd set of code I was working with, I have my List right under partial class, but this is all contained in a method.
private void DeleteRecord()
{
ListBox lstRecords = new ListBox();
List<object> employee = new List<object>();
employee.RemoveAt(lstRecords.SelectedIndex);
lstRecords.Items.RemoveAt(lstRecords.SelectedIndex);
}
So far I haven't gotten either set of code to work the way I would like it to, I'm obviously doing something wrong.
I have a few other blocks of code I played around with but these seemed to be headed in the right direction.
Eventually I'll need to be able to double click an item in the list to pull up the properties menu.
Your code runs fine you just have to make some small changes.
The first code block is Ok however I dont know where your lstRecords are.
But have a look at this just copy the code and run it after you have some records in your employee object.
It's createing a listbox in code then adds it to the form(Winforms) and having the lstRecords globaly.
ListBox lstRecords;
private void IntializeDemoListbox()
{
lstRecords = new ListBox();
this.Controls.Add(lstRecords);
foreach (var item in employee)
{
lstRecords.Items.Add(item);
}
}
And then you will be able to use your first set of code the other set will be like this.
private void DeleteRecord()
{
employee.RemoveAt(lstRecords.SelectedIndex);
lstRecords.Items.RemoveAt(lstRecords.SelectedIndex);
}
What you want to do is bind your ListBox to you List of employees. This post shows the binding and the comments shows the removing code as well. The idea is that when you remove an item from the DataSource, then you won't see it in the ListBox.
Binding Listbox to List<object>
The problem with the DeleteRecord() method is that the lstRecords object you just created isn't the ListBox that is on the form.
I have a BindingList< KeyValuePair < string, string > > that is bound to a ComboBox control. Based on some conditions, the BindingList will be added a new KeyValuePair. Now, the Newly added item shows up at index 0 of the Combobox, instead of at the end.
While debugging, I found that the BindingList has got the right order. (i.e, the new KeyValuePair is appended)
Also, I check the SelectedValue of the ComboBox in it's SelectedIndexChanged handler and it seems to be not of the ListItem that got selected. Instead, it is that of the supposed ListItem, if the ComboBox had got the right order as in its DataSource, - the BindingList..
The code is a small part of a large project.. Plz let me know if the question is not clear. I can put the relevant parts of the code as per our context.
How could something like this happen? What can I do differently?
I have this class something like this.
public class DropdownEntity
{
//removed all except one members and properties
private string frontEndName
public string FrontEndName
{
get {return this.frontEndName; }
set {this.frontEndName= value; }
}
//One Constructor
public DropdownEntity(string _frontEndName)
{
this.FrontEndName = _frontEndName;
//Removed code which initializes several members...
}
//All methods removed..
public override string ToString()
{
return frontEndName;
}
}
In my windows form, I have a tab control with several tabs. In one of the tabs pages, I have a DataGridView. The user is supposed to edit the cells and click on a Next - button. Then, some processing will be done, and the TabControl will be navigated to the next tab page.
The next tab page has the combobox that has the problem I mentioned. This page also has a back button, which will take back.. the user can modify the gridview cells again.. and click on the next button. This is when the order gets messed up.
I am posting here the Click event handler of the Next Button.. Along with the class, with the rest of the code removed.
public partial class AddUpdateWizard : Form
{
//Removed all members..
BindingList<KeyValuePair<string, string>> DropdownsCollection;
Dictionary<string, DropdownEntity> DropdownsDict;
//Defined in a partial definition of the class..
DataGridView SPInsertGridView = new DataGridView();
ComboBox DropdownsCmbBox = new ComboBox();
Button NextBtn2 = new Button();
Button BackBtn3 = new Button();
//Of course these controls are added to one of the panels
public AddUpdateWizard(MainForm mainForm)
{
InitializeComponent();
DropdownsDict = new Dictionary<string, DropdownEntity>();
}
private void NextBtn2_Click(object sender, EventArgs e)
{
string sqlArgName;
string frontEndName;
string fieldType;
for (int i = 0; i < SPInsertGridView.Rows.Count; i++)
{
sqlArgName = "";
frontEndName = "";
fieldType = "";
sqlArgName = SPInsertGridView.Rows[i].Cells["InsertArgName"].Value.ToString().Trim();
if (SPInsertGridView.Rows[i].Cells["InsertArgFrontEndName"].Value != null)
{
frontEndName = SPInsertGridView.Rows[i].Cells["InsertArgFrontEndName"].Value.ToString().Trim();
}
if (SPInsertGridView.Rows[i].Cells["InsertArgFieldType"].Value != null)
{
fieldType = SPInsertGridView.Rows[i].Cells["InsertArgFieldType"].Value.ToString().Trim();
}
//I could have used an enum here, but this is better.. for many reasons.
if (fieldType == "DROPDOWN")
{
if (!DropdownsDict.ContainsKey(sqlArgName))
DropdownsDict.Add(sqlArgName, new DropdownEntity(frontEndName));
else
DropdownsDict[sqlArgName].FrontEndName = frontEndName;
}
else
{
if (fieldType == "NONE")
nonFieldCount++;
if (DropdownsDict.ContainsKey(sqlArgName))
{
DropdownsDict.Remove(sqlArgName);
}
}
}
//DropdownsCollection is a BindingList<KeyValuePair<string, string>>.
//key in the BindingList KeyValuePair will be that of the dictionary.
//The value will be from the ToString() function of the object in the Dictionary.
DropdownsCollection = new BindingList<KeyValuePair<string,string>>(DropdownsDict.Select(kvp => new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString())).ToList());
DropdownsCmbBox.DataSource = DropdownsCollection;
DropdownsCmbBox.DisplayMember = "Value";
DropdownsCmbBox.ValueMember = "Key";
//Go to the next tab
hiddenVirtualTabs1.SelectedIndex++;
}
private void BackBtn3_Click(object sender, EventArgs e)
{
hiddenVirtualTabs1.SelectedIndex--;
}
//On Selected Index Changed of the mentioned Combobox..
private void DropdownsCmbBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropdownsCmbBox.SelectedValue != null)
{
if (DropdownsDict.ContainsKey((DropdownsCmbBox.SelectedValue.ToString())))
{
var dropdownEntity = DropdownsDict[DropdownsCmbBox.SelectedValue.ToString()];
DropdownEntityGB.Text = "Populate Dropdowns - " + dropdownEntity.ToString();
//Rest of the code here..
//I see that the Datasource of this ComboBox has got the items in the right order.
// The Combobox's SelectedValue is not that of the selected item. Very Strange behavior!!
}
}
}
}
The very first time the user clicks the Next Button, it's fine. But if he clicks the Back Button again and changes the Data Grid View cells.. The order will be gone.
I know, it can be frustrating to look at. It's a huge thing to ask for help. Any help would be greatly appreciated!
Please let me know if you need elaboration at any part.
Thanks a lot :)
I think you have two problems here.
First, if you want to retain the order of the items you should use an OrderedDictionary instead of a regular one. A normal collection will not retain the order of the items when you use Remove method. You can see more info about this related to List here.
You could use such dictionary like this:
DropDownDict = new OrderedDictionary();
// Add method will work as expected (as you have it now)
// Below you have to cast it before using Select
DropDownCollection = new BindingList<KeyValuePair<string, string>>(DropDownDict.Cast<DictionaryEntry>().Select(kvp => new KeyValuePair<string, string>(kvp.Key.ToString(), kvp.Value.ToString())).ToList());
The second problem could be that you change the display name (FrontEndName) of already existing items, but the key is preserved. When you add a new item, try to remove the old one that you're not using anymore and add a new item.
The Sorted Property of the Combobox is set to True! I didn't check that until now. I messed up. Terribly sorry for wasting your time Adrian. Thanks a lot for putting up with my mess here.. :)
I have a method that adds items to my listbox called refreshInterface which is called as soon as the programe starts, adding names of homeforms in the listbox using the FormItems class, here is the rereshInterface method below
public void refreshInterface()
{
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var forms = new FormItems(homeForms);
listBox1.Items.Add(forms);
}
}
The FormItems class is this below
public class FormItems
{
public DataSet1.xspGetAnalysisUsageTypesRow types { get; set; }
public FormItems(DataSet1.xspGetAnalysisUsageTypesRow usageTypes)
{
types = usageTypes;
}
public override string ToString()
{
// returns the rows that are relating to types.xlib_ID
var libtyps = types.GetxAnalysisUsageRows();
var cnt = 0;
foreach (DataSet1.xAnalysisUsageRow ty in libtyps)
{
//returns true if ty is null
bool typeNull = ty.Isxanu_DefaultNull();
// if its false, if xanu_Default is set
if (!typeNull)
{
cnt += 1;
}
}
var ret = String.Format("set {0} [Set: {1}]", types.xlib_Desc, cnt);
//return this.types.xlib_Desc;
return ret;
}
}
Each listbox (the listbox is on the left of the homeform) item has a number of reports that can be added to it, so for instance, i select an homeform from my listbox, there are 12 textboxes on the right hand side and each textbox has a pair of buttons which are Browse and Clear. If I click on the browse button a new form appears, and i select a report from that form and add it to a particular textbox, the count for that homeform should update, and i clear a textbox for a particular homeform, the count should also update.
At the moment when i debug the application, it shows me the count of each Homeform depending on the amount of reports added to the homeform, but while the programe is running, if i add a new report to a homeform, the count does not update until i restart the debug session. I was told about using a Databinding method but not sure of how i could use it here
How do i ge my listbox item to update ?
You should probably look into binding. Here is a good place to start:
http://www.codeproject.com/Articles/140621/WPF-Tutorial-Concept-Binding
If you want a GUI to respond to data changes then binding is your best friend.
You should bind List Box component source to Observable Collection, every update you do to Observable Collection will update List Box data.
Might not be exact but should give you an idea.
public void refreshInterface()
{
Dictionary<int,string> items = new Dictionary<int,string>();
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var formitem = new FormItems(homeForms);
items.Add(formitem.someprop, formitem.toString());
}
listbox.DataSource = items;
listbox.DisplayMember = "Value";
listbox.ValueMember = "Key";
}