Q-M
asked on
C# WinForms - Clearing the list of items in ListBox when DataBinding to a Dictionary
Hello all,
I'm having problems getting my code to work. I have a ListBox where I DataBind a Dictionary<int, string> to it.
When there are items in the Dictionary the binding works great, when there are items already in the ListBox and I try to update the binding with an empty Dictionary, the items doesn't get cleared in the Listbox even though I go ListBox.DataBindings.Clear ().
Any ideas on what I'm doing wrong?
I'm having problems getting my code to work. I have a ListBox where I DataBind a Dictionary<int, string> to it.
When there are items in the Dictionary the binding works great, when there are items already in the ListBox and I try to update the binding with an empty Dictionary, the items doesn't get cleared in the Listbox even though I go ListBox.DataBindings.Clear
Any ideas on what I'm doing wrong?
public void UpdateSearchItems(PublicEvaluationReportSearchOptions searchOption, Dictionary<int, string> selectedOptions)
{
//Only add items when the user has made selections
if (selectedOptions.Count > 0)
{
switch (searchOption)
{
case PublicEvaluationReportSearchOptions.Courses:
lbxSelectedCourses.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedCourses.DisplayMember = "Value";
lbxSelectedCourses.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Events:
lbxSelectedEvents.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedEvents.DisplayMember = "Value";
lbxSelectedEvents.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Locations:
lbxSelectedLocations.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedLocations.DisplayMember = "Value";
lbxSelectedLocations.ValueMember = "Key";
break;
}
}
else
{
//Clear the list box items
switch (searchOption)
{
case PublicEvaluationReportSearchOptions.Courses:
lbxSelectedCourses.DataBindings.Clear();
break;
case PublicEvaluationReportSearchOptions.Events:
lbxSelectedEvents.DataBindings.Clear();
break;
case PublicEvaluationReportSearchOptions.Locations:
lbxSelectedLocations.DataBindings.Clear();
break;
}
}
}
ASKER
Thanks roxviper,
That doesn't work becuase the listbox has been databind and it throws an exception, the Items can't be cleared because of the databind.
That doesn't work becuase the listbox has been databind and it throws an exception, the Items can't be cleared because of the databind.
ASKER
Ok, So I tried setting the DataSource = null, the problem is that after that is done, when I try to bind it again the ListBox doesn't display anything
ASKER
Sorry, I didn't mention that I'm looking for a .net 2.0 solution
I don't understand the problem here.. This is a simple example, and it sets/resets the data source for listbox without any problem. Can you please exaplin better where the problem is:
private void btAdd_Click(object sender, EventArgs e)
{
Dictionary<int, string> list = new Dictionary<int, string>();
list.Add(0, "a");
list.Add(1, "b");
list.Add(2, "c");
listBox1.DataSource = new BindingSource(list, null);
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
}
private void btnRemove_Click(object sender, EventArgs e)
{
listBox1.DataSource = null;
}
ASKER
Priest04,
After the DataSource has been set to null, the next time I go to set the DataSource with a new list of selectedOptions, the ListBox doesn't show the new list.
After the DataSource has been set to null, the next time I go to set the DataSource with a new list of selectedOptions, the ListBox doesn't show the new list.
What if you bind an empty list exactly the way you do with the above one?
Dictionary<int, string> list = new Dictionary<int, string>();
listBox1.DataSource = new BindingSource(list, null);
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
Dictionary<int, string> list = new Dictionary<int, string>();
listBox1.DataSource = new BindingSource(list, null);
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
ASKER
It throws an exception when I try to bind an empty list to it
But if try simple example I gave above, you click btnAdd to set Datasrouce, then you click btnRemove to set datasource to null, and then again btnAdd to set it again, and no problem occur. So, it is not a problem with actual binding?
ASKER
Hi Priest04,
After setting the datasource to null, and then when I tried adding it again - the Listbox doesn't show anything - it stays empty and doesn't show anything.
After setting the datasource to null, and then when I tried adding it again - the Listbox doesn't show anything - it stays empty and doesn't show anything.
Q-M, its important to understand this: is this happening with your code, or mine?
ASKER
I 've gone and changed my lines of code from:
lbxSelectedCourses.DataBin dings.Clea r();
to
lbxSelectedCourses.DataSou rce = null;
Try to run it, and after I set the DataSource to null, I tried binding a new Dictionary list that has items in it, and the listbox didn't show anything.
lbxSelectedCourses.DataBin
to
lbxSelectedCourses.DataSou
Try to run it, and after I set the DataSource to null, I tried binding a new Dictionary list that has items in it, and the listbox didn't show anything.
Ok, but first we need to clear something - this is not a problem with actual databinding. This I say because, if you just paste my code into new project, you will see that it works flawlessly. So the problem is proably somewhere else, you have several if and switch statements, so maybe the problem is with them. You need to put some breakpoint and see what part of code will run, check if Dictionary actually has items in it...
ASKER
After debugging and adding breakpoints in my code, I can verify that everything is working fine with all the switch statements I have in my code.
I did notice that after setting lbxSelectedLocations.DataS ource = null; to the Locations listbox
I added the following code:
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items )
{
MessageBox.Show(selItem.Va lue);
}
And it popped up with the list of listbox items, even though I set the datasource to null.
I did notice that after setting lbxSelectedLocations.DataS
I added the following code:
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items
{
MessageBox.Show(selItem.Va
}
And it popped up with the list of listbox items, even though I set the datasource to null.
case PublicEvaluationReportSearchOptions.Locations:
lbxSelectedLocations.DataSource = null;
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items)
{
MessageBox.Show(selItem.Value);
}
break;
Can you please post the complete code here, so we can test this?
ASKER
Ok here is the main form where I display the listboxes
public partial class PublicCourseEvaluationReport : System.Windows.Forms.Form
{
public PublicCourseEvaluationReport()
{
InitializeComponent();
}
public void LoadThisForm()
{
InitializeDataGridView();
this.MdiParent = ApplicationForms.MainFormRef;
this.Show();
}
private void InitializeDataGridView()
{
//Get XML Style template from DB
dvgEvaluationResults.Columns.Clear();
WebValues wbTemplate = WebValues.GetWebValue("PublicCourseEvalDisplayTemplate");
if (string.IsNullOrEmpty(wbTemplate.WebVal_Value))
{
//Load these default settings
//Set the selection background color for all the cells in Master Grid
dvgEvaluationResults.DefaultCellStyle.SelectionBackColor = ColorTranslator.FromHtml("#0054E3");
dvgEvaluationResults.DefaultCellStyle.SelectionForeColor = ColorTranslator.FromHtml("#000000");
//Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
//value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
dvgEvaluationResults.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty;
//Set Row Styles
dvgEvaluationResults.RowsDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#FFFFFF");
dvgEvaluationResults.AlternatingRowsDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5DEE1");
//Set Column Header Style
DataGridViewCellStyle headerCellStyle = new DataGridViewCellStyle();
headerCellStyle.BackColor = ColorTranslator.FromHtml("#577B87");
headerCellStyle.ForeColor = ColorTranslator.FromHtml("#FFFFFF");
using (Font fnt = new Font("Verdana", 8))
{
headerCellStyle.Font = fnt;
}
dvgEvaluationResults.ColumnHeadersDefaultCellStyle = headerCellStyle;
}
//else
//{
// //Go through the XML Template and set the datagrid settings
// string cellStyle = "";
//}
//Add Columns to DataGrid
DataGridViewColumn column;
column = new DataGridViewTextBoxColumn();
column.Name = "Evnt_ID";
column.HeaderText = "Event ID";
column.Width = 80;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Evnt_Dates";
column.HeaderText = "Event Dates";
column.Width = 120;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Course_Title";
column.HeaderText = "Course Title";
column.Width = 400;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Location";
column.HeaderText = "Location";
column.Width = 100;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Venue";
column.HeaderText = "Venue";
column.Width = 250;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Instructors";
column.HeaderText = "Instructor(s)";
column.Width = 150;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Date_Submitted";
column.HeaderText = "Date Submitted";
column.Width = 120;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Participant_Name";
column.HeaderText = "Participant Name";
column.Width = 150;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Company";
column.HeaderText = "Company";
column.Width = 250;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Question_Number";
column.HeaderText = "#";
column.Width = 30;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Question_Text";
column.HeaderText = "Question Text";
column.Width = 400;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Question_Answer";
column.HeaderText = "Question Answer";
column.Width = 150;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "Question_Comment";
column.HeaderText = "Question Comment";
column.Width = 450;
dvgEvaluationResults.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "InHouse_Reference";
column.HeaderText = "InHouse Reference";
column.Width = 200;
dvgEvaluationResults.Columns.Add(column);
}
public void UpdateSearchItems(PublicEvaluationReportSearchOptions searchOption, Dictionary<int, string> selectedOptions)
{
//Only add items when the user has made selections
if (selectedOptions.Count > 0)
{
switch (searchOption)
{
case PublicEvaluationReportSearchOptions.Courses:
lbxSelectedCourses.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedCourses.DisplayMember = "Value";
lbxSelectedCourses.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Events:
lbxSelectedEvents.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedEvents.DisplayMember = "Value";
lbxSelectedEvents.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Locations:
lbxSelectedLocations.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedLocations.DisplayMember = "Value";
lbxSelectedLocations.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Venues:
lbxSelectedVenues.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedVenues.DisplayMember = "Value";
lbxSelectedVenues.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Questions:
lbxSelectedQuestions.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedQuestions.DisplayMember = "Value";
lbxSelectedQuestions.ValueMember = "Key";
break;
case PublicEvaluationReportSearchOptions.Answers:
lbxSelectedAnswers.DataSource = new BindingSource(selectedOptions, null);
lbxSelectedAnswers.DisplayMember = "Value";
lbxSelectedAnswers.ValueMember = "Key";
break;
}
}
else
{
//Clear the list box items
switch (searchOption)
{
case PublicEvaluationReportSearchOptions.Courses:
lbxSelectedCourses.DataSource = null;
break;
case PublicEvaluationReportSearchOptions.Events:
lbxSelectedEvents.DataSource = null;
break;
case PublicEvaluationReportSearchOptions.Locations:
lbxSelectedLocations.DataSource = null;
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items)
{
MessageBox.Show(selItem.Value);
}
break;
case PublicEvaluationReportSearchOptions.Venues:
lbxSelectedVenues.DataSource = null;
break;
case PublicEvaluationReportSearchOptions.Questions:
lbxSelectedQuestions.DataSource = null;
break;
case PublicEvaluationReportSearchOptions.Answers:
lbxSelectedAnswers.DataSource = null;
break;
}
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
//TODO: Get all items in the ListBoxes and pass them to the search method
Dictionary<int, string> selCourses, selEvents, selLocations, selVenues, selQuestions, selAnswers;
selCourses = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedCourses.Items){ selCourses.Add(pair.Key, pair.Value); }
selEvents = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedEvents.Items) { selEvents.Add(pair.Key, pair.Value); }
selLocations = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedLocations.Items) { selLocations.Add(pair.Key, pair.Value); }
selVenues = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedVenues.Items) { selVenues.Add(pair.Key, pair.Value); }
selQuestions = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedQuestions.Items) { selQuestions.Add(pair.Key, pair.Value); }
selAnswers = new Dictionary<int, string>();
foreach (KeyValuePair<int, string> pair in lbxSelectedAnswers.Items) { selAnswers.Add(pair.Key, pair.Value); }
}
private void formLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//Determine which LinkLabel raised the event
LinkLabel sendingLabel = (LinkLabel)sender;
Dictionary<int, string> selItems = new Dictionary<int, string>();
Dictionary<int, string> selParItems = new Dictionary<int, string>();
Reports.PublicCourseEvaluationReportSelection reportSearch = new PublicCourseEvaluationReportSelection();
switch (sendingLabel.Name)
{
case "lkblCourses":
foreach (KeyValuePair<int, string> selItem in lbxSelectedCourses.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Courses, selItems, null);
break;
case "lkblEvents":
//Get List of Events Selected
foreach (KeyValuePair<int, string> selItem in lbxSelectedEvents.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
foreach (KeyValuePair<int, string> selItem in lbxSelectedCourses.Items)
{
selParItems.Add(selItem.Key, selItem.Value);
}
//Get List Courses Selected so that we can load the list of Events based off Courses
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Events, selItems, selParItems);
break;
case "lkblLocations":
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Locations, selItems, null);
break;
case "lkblVenues":
//Get List of Venues Selected
foreach (KeyValuePair<int, string> selItem in lbxSelectedVenues.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
//Get List of Locations Selected so that we can load the list of venues based off locations
foreach (KeyValuePair<int, string> selItem in lbxSelectedLocations.Items)
{
selParItems.Add(selItem.Key, selItem.Value);
}
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Venues, selItems, selParItems);
break;
case "lkblQuestions":
foreach (KeyValuePair<int, string> selItem in lbxSelectedQuestions.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Questions, selItems, null);
break;
case "lkblAnswers":
//Get List of Answers Selected
foreach (KeyValuePair<int, string> selItem in lbxSelectedAnswers.Items)
{
selItems.Add(selItem.Key, selItem.Value);
}
//Get List of Questions Selected so that we can load the list of answers based off the questions
foreach (KeyValuePair<int, string> selItem in lbxSelectedQuestions.Items)
{
selParItems.Add(selItem.Key, selItem.Value);
}
reportSearch.LoadThisForm(this, PublicEvaluationReportSearchOptions.Answers, selItems, selParItems);
break;
}
}
}
ASKER
This is the 2nd form where we select the search options
public partial class PublicCourseEvaluationReportSelection : System.Windows.Forms.Form
{
PublicEvaluationReportSearchOptions searchOption;
PublicCourseEvaluationReport parentForm;
public PublicCourseEvaluationReportSelection()
{
InitializeComponent();
}
/// <summary>
/// Methhod to load this form based on the search option and selected items
/// </summary>
/// <param name="parent">Parent Form</param>
/// <param name="option">PublicEvaluationReportSearchOptions</param>
/// <param name="selectedOptions">Selected Search Options</param>
/// <param name="selectedParentOptions">Selected Parent Search Options</param>
public void LoadThisForm(Form parent, PublicEvaluationReportSearchOptions option, Dictionary<int, String> selectedOptions, Dictionary<int, String> selectedParentOptions)
{
//Set Form values
parentForm = (PublicCourseEvaluationReport)parent;
searchOption = option;
lblSearch.Text = "Search Options";
lbxOptions.DataBindings.Clear();
Dictionary<int, string> items = new Dictionary<int, string>();
StringBuilder strNoItems = new StringBuilder();
switch (searchOption)
{
case PublicEvaluationReportSearchOptions.Courses:
lblSearch.Text = "Search Courses";
//Load list of all courses into ListBox
items = Course.GetEnabledCoursesList();
if (items.Count <= 0) { strNoItems.Append(" - No Courses found"); }
break;
case PublicEvaluationReportSearchOptions.Events:
lblSearch.Text = "Search Events";
//Load list of all completed Events, based on the selected courses
items = Event.GetCompletedEvents(DateTime.Now.AddYears(-3), DateTime.Now, selectedParentOptions);
if (items.Count <= 0) { strNoItems.Append(" - No Completed Events found"); }
break;
case PublicEvaluationReportSearchOptions.Locations:
lblSearch.Text = "Search Locations";
//Load list of all Locations
items = StaffAdmin.DAL.Location.GetLocationsList(true);
if (items.Count <= 0) { strNoItems.Append(" - No Locations found"); }
break;
case PublicEvaluationReportSearchOptions.Venues:
lblSearch.Text = "Search Venues";
//Load list of Venues based on selected Locations
items = Venue.GetVenueListFromLocations(selectedParentOptions);
if (items.Count <= 0) { strNoItems.Append(" - No Venues found"); }
break;
case PublicEvaluationReportSearchOptions.Questions:
lblSearch.Text = "Search Evaluation Questions";
//Load list of all Public Course Evaluation Questions
items = CourseEvaluationQuestion.GetQuestionTextList(500);
if (items.Count <= 0) { strNoItems.Append(" - No Evaluation Questions found"); }
break;
case PublicEvaluationReportSearchOptions.Answers:
lblSearch.Text = "Search Evaluation Answers";
//Load list of all Public Course Evaluation Question Answers based on selected Questions
items = CourseEvaluationAnswers.GetAnswerListFromMultipleQuestions(selectedParentOptions, (selectedParentOptions.Count == 0 ? true : false));
if (items.Count <= 0) { strNoItems.Append(" - No Evaluation Answers found"); }
break;
}
if (items.Count > 0)
{
//Bind list to the ListBox
lbxOptions.DataSource = new BindingSource(items, null);
lbxOptions.DisplayMember = "Value";
lbxOptions.ValueMember = "Key";
lbxOptions.SelectedItems.Clear();
//Set selected items
if (selectedOptions.Count > 0)
{
int index = 0;
foreach (KeyValuePair<int, string> pairs in selectedOptions)
{
index = lbxOptions.Items.IndexOf(pairs);
if (index >= 0) { lbxOptions.SetSelected(index, true); }
}
}
}
else{ lblSearch.Text += strNoItems.ToString(); }
this.Show();
}
/// <summary>
/// Clear selected items in the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClearSelected_Click(object sender, EventArgs e)
{
lbxOptions.SelectedItems.Clear();
}
/// <summary>
/// Method that returns a list of selected search items to the parent form and closes this form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelect_Click(object sender, EventArgs e)
{
Dictionary<int, string> selItems = new Dictionary<int, string>();
if (lbxOptions.SelectedItems.Count > 0)
{
foreach (KeyValuePair<int, string> selItem in lbxOptions.SelectedItems)
{
selItems.Add(selItem.Key, selItem.Value);
}
}
parentForm.UpdateSearchItems(searchOption, selItems);
this.Close();
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Priest04,
The attached code I had already made the changes to set the listboxe's DataSource = null and I was still getting the same problem.
I won't have time today to look through your code but I'll run through it on Monday.
The attached code I had already made the changes to set the listboxe's DataSource = null and I was still getting the same problem.
I won't have time today to look through your code but I'll run through it on Monday.
No, you still had it here:
public void LoadThisForm(Form parent, PublicEvaluationReportSear chOptions option, Dictionary<int, String> selectedOptions, Dictionary<int, String> selectedParentOptions)
{
//Set Form values
parentForm = (PublicCourseEvaluationRep ort)parent ;
searchOption = option;
lblSearch.Text = "Search Options";
lbxOptions.DataBindings.Cl ear();
and here
/// <summary>
/// Clear selected items in the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClearSelected_Click(obj ect sender, EventArgs e)
{
lbxOptions.SelectedItems.C lear();
}
public void LoadThisForm(Form parent, PublicEvaluationReportSear
{
//Set Form values
parentForm = (PublicCourseEvaluationRep
searchOption = option;
lblSearch.Text = "Search Options";
lbxOptions.DataBindings.Cl
and here
/// <summary>
/// Clear selected items in the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClearSelected_Click(obj
{
lbxOptions.SelectedItems.C
}
ASKER
Tested it out and still was getting the same problem. So I went and looked at the selectionMode properties on each of the listboxes and changed them from None to MultiSimple and that did the trick.
Thanks for all your help guys
Thanks for all your help guys
try lbxSelectedLocations.Items