Listbox clears all items during datasource change - c#

When I change the datasource of my Listbox all items are cleared, when loading new data into this Listbox it stays clear.
I have another ListBox right new to this one with the same refresh code but that one refreshes perfectly.
private void RefreshContacts()
{
this.ListContacts.DataSource = null;
this.ListContacts.DataSource = this.contacts;
this.BoxCountContacts.Text = this.ListContacts.Items.Count.ToString();
}
Anyone have an idea how to fix the listbox from being cleared and bugged?
Here is the full refresh codes of the two listboxes
private Contact[] contacts, feed; private Boolean isFeed;
internal ArcFeed()
{
this.InitializeComponent();
this.contacts = this.feed = new Contact[0];
}
private void RefreshForm(Boolean isFeed)
{
if (isFeed)
{
this.RefreshFeed();
}
else
{
this.RefreshContacts();
}
}
private void RefreshContacts()
{
this.ListContacts.DataSource = null;
this.ListContacts.DataSource = this.contacts;
this.BoxCountContacts.Text = this.ListContacts.Items.Count.ToString();
}
private void RefreshFeed()
{
this.ListFeed.DataSource = null;
this.ListFeed.DataSource = this.feed;
this.BoxCountFeed.Text = this.ListFeed.Items.Count.ToString();
}
private void OpenFile()
{
if (this.isFeed)
{
this.BoxFileFeed.Text = this.DialogOpen.FileName;
this.feed = ArcBuzz.Load(this.DialogOpen.FileName);
}
else
{
this.BoxFileContacts.Text = this.DialogOpen.FileName;
this.contacts = ArcBuzz.Load(this.DialogOpen.FileName);
}
this.RefreshForm(this.isFeed);
}
All code is debugged and follows it's course properly, I don't see any errors, the correct listbox's datasource are set and changed.

Just to make sure, have you checked that there are actually items in the contacts collection?
Also, if you've got two Listboxes, double check that you are using the right Listbox in each of the refresh code sections.
Sounds stupid, but its silly mistakes like this that get overlooked a lot of the time. With databinding its usually something small like this stopping it working.

Related

ListBox Showing First Item Only

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());

The BindingList Datasource of a Combobox refreshes correctly but the Combobox displays items in the wrong order

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.. :)

fire (call) method, when scrollviewer scrolled to its end

after being googled a lot, finally i am going to ask this to you guys.
i'v created scrollviewer, which contains items(listboxItems) and these items fetching from the webservices. but at once only 5 items can fetched. so initially it'll be 5 items, then next 5(appended to the scrollviewer) and then next 5 and so on......
note:-here listBoxitems are used inside the scrollviewer, not the listbox
data fetched from webservice also contains--->
total items
numResults (current number of items fetched)
now suppose my method to fetch data is--->
getData(int nextResult)
{
// some code to fetch the data
}
where nextResult is next item number(ex:- nextResult is 6, if requesting 2nd time)
but i am unable to write the code to detect that the user scrolled the scrollviewer to the end & then a method to be called or fired, whatever say!
i'v been badly confused among scrollviewer's VerticalOffset, ExtentHeight, ViewportHeight, ScrollableHeight etc, about to use them & calculate desired information to achieve above requirements.
so if anyone knows about the same or used ever scrollviwer, than please post answer.
I achieved it by registering new DependencyProperty ListVerticalOffset with appropriate event:
// Constructor
public MainPage()
{
InitializeComponent();
ListVerticalOffsetProperty = DependencyProperty.Register("ListVerticalOffset", typeof(double), typeof(MainPage), new PropertyMetadata(OnListVerticalOffsetChanged));
YourScrollViewer.Loaded += YourScrollViewer_Loaded;
}
void YourScrollViewer_Loaded(object sender, RoutedEventArgs e)
{
var binding = new Binding
{
Source = YourScrollViewer,
Path = new PropertyPath("VerticalOffset"),
Mode = BindingMode.OneWay
};
SetBinding(ListVerticalOffsetProperty, binding);
}
private void OnListVerticalOffsetChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var atBottom = YourScrollViewer.VerticalOffset >= YourScrollViewer.ScrollableHeight;
if (atBottom) MessageBox.Show("End");
}
public readonly DependencyProperty ListVerticalOffsetProperty;
public double ListVerticalOffset
{
get { return (double)GetValue(ListVerticalOffsetProperty); }
set { SetValue(ListVerticalOffsetProperty, value); }
}
May be this solution or it's realization is not optimal, but it's working for me.

c# how do i refresh items in my listbox

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";
}

Data table columns become out of order after changing data source

This is kind of a oddball problem so I will try to describe the best that I can.
I have a DataGridView that shows a list of contracts and various pieces of information about them. There are three view modes: Contract Approval, Pre-Production, and Production. Each mode has it's own set of columns that need to be displayed.
What I have been doing is I have three radio buttons one for each contract style. all of them fire their check changed on this function
private void rbContracts_CheckedChanged(object sender, EventArgs e)
{
dgvContracts.Columns.Clear();
if (((RadioButton)sender).Checked == true)
{
if (sender == rbPreProduction)
{
dgvContracts.Columns.AddRange(searchSettings.GetPreProductionColumns());
this.contractsBindingSource.DataMember = "Preproduction";
this.preproductionTableAdapter.Fill(this.searchDialogDataSet.Preproduction);
}
else if (sender == rbProduction)
{
dgvContracts.Columns.AddRange(searchSettings.GetProductionColumns());
this.contractsBindingSource.DataMember = "Production";
this.productionTableAdapter.Fill(this.searchDialogDataSet.Production);
}
else if (sender == rbContracts)
{
dgvContracts.Columns.AddRange(searchSettings.GetContractsColumns());
this.contractsBindingSource.DataMember = "Contracts";
this.contractsTableAdapter.Fill(this.searchDialogDataSet.Contracts);
}
}
}
Here is the GetxxxColumns function
public DataGridViewColumn[] GetPreProductionColumns()
{
this.dgvTxtPreAccount.Visible = DgvTxtPreAccountVisable;
this.dgvTxtPreImpromedAccNum.Visible = DgvTxtPreImpromedAccNumVisable;
this.dgvTxtPreCreateDate.Visible = DgvTxtPreCreateDateVisable;
this.dgvTxtPreCurrentSoftware.Visible = DgvTxtPreCurrentSoftwareVisable;
this.dgvTxtPreConversionRequired.Visible = DgvTxtPreConversionRequiredVisable;
this.dgvTxtPreConversionLevel.Visible = DgvTxtPreConversionLevelVisable;
this.dgvTxtPreProgrammer.Visible = DgvTxtPreProgrammerVisable;
this.dgvCbxPreEdge.Visible = DgvCbxPreEdgeVisable;
this.dgvCbxPreEducationRequired.Visible = DgvCbxPreEducationRequiredVisable;
this.dgvTxtPreTargetMonth.Visible = DgvTxtPreTargetMonthVisable;
this.dgvCbxPreEdgeDatesDate.Visible = DgvCbxPreEdgeDatesDateVisable;
this.dgvTxtPreStartDate.Visible = DgvTxtPreStartDateVisable;
this.dgvTxtPreUserName.Visible = DgvTxtPreUserNameVisable;
this.dgvCbxPreProductionId.Visible = DgvCbxPreProductionIdVisable;
return new System.Windows.Forms.DataGridViewColumn[] {
this.dgvTxtPreAccount,
this.dgvTxtPreImpromedAccNum,
this.dgvTxtPreCreateDate,
this.dgvTxtPreCurrentSoftware,
this.dgvTxtPreConversionRequired,
this.dgvTxtPreConversionLevel,
this.dgvTxtPreProgrammer,
this.dgvCbxPreEdge,
this.dgvCbxPreEducationRequired,
this.dgvTxtPreTargetMonth,
this.dgvCbxPreEdgeDatesDate,
this.dgvTxtPreStartDate,
this.dgvTxtPreUserName,
this.dgvCbxPreProductionId,
this.dgvTxtCmnHold,
this.dgvTxtCmnConcern,
this.dgvTxtCmnAccuracyStatus,
this.dgvTxtCmnEconomicStatus,
this.dgvTxtCmnSoftwareStatus,
this.dgvTxtCmnServiceStatus,
this.dgvTxtCmnHardwareStatus,
this.dgvTxtCmnAncillaryStatus,
this.dgvTxtCmnFlowStatus,
this.dgvTxtCmnImpromedAccountNum,
this.dgvTxtCmnOpportunityId};
}
public DataGridViewColumn[] GetProductionColumns()
{
this.dgvcTxtProAccount.Visible = DgvTxtProAccountVisable;
this.dgvTxtProImpromedAccNum.Visible = DgvTxtProImpromedAccNumVisable;
this.dgvTxtProCreateDate.Visible = DgvTxtProCreateDateVisable;
this.dgvTxtProConvRequired.Visible = DgvTxtProConvRequiredVisable;
this.dgvTxtProEdgeRequired.Visible = DgvTxtProEdgeRequiredVisable;
this.dgvTxtProStartDate.Visible = DgvTxtProStartDateVisable;
this.dgvTxtProHardwareRequired.Visible = DgvTxtProHardwareReqiredVisable;
this.dgvTxtProStandardDate.Visible = DgvTxtProStandardDateVisable;
this.dgvTxtProSystemScheduleDate.Visible = DgvTxtProSystemScheduleDateVisable;
this.dgvTxtProHwSystemCompleteDate.Visible = DgvTxtProHwSystemCompleteDateVisable;
this.dgvTxtProHardwareTechnician.Visible = DgvTxtProHardwareTechnicianVisable;
return new System.Windows.Forms.DataGridViewColumn[] {
this.dgvcTxtProAccount,
this.dgvTxtProImpromedAccNum,
this.dgvTxtProCreateDate,
this.dgvTxtProConvRequired,
this.dgvTxtProEdgeRequired,
this.dgvTxtProStartDate,
this.dgvTxtProHardwareRequired,
this.dgvTxtProStandardDate,
this.dgvTxtProSystemScheduleDate,
this.dgvTxtProHwSystemCompleteDate,
this.dgvTxtProHardwareTechnician,
this.dgvTxtCmnHold,
this.dgvTxtCmnConcern,
this.dgvTxtCmnAccuracyStatus,
this.dgvTxtCmnEconomicStatus,
this.dgvTxtCmnSoftwareStatus,
this.dgvTxtCmnServiceStatus,
this.dgvTxtCmnHardwareStatus,
this.dgvTxtCmnAncillaryStatus,
this.dgvTxtCmnFlowStatus,
this.dgvTxtCmnImpromedAccountNum,
this.dgvTxtCmnOpportunityId};
}
public DataGridViewColumn[] GetContractsColumns()
{
this.dgvTxtConAccount.Visible = this.DgvTxtConAccountVisable;
this.dgvTxtConAccuracyStatus.Visible = this.DgvTxtConAccuracyStatusVisable;
this.dgvTxtConCreateDate.Visible = this.DgvTxtConCreateDateVisable;
this.dgvTxtConEconomicStatus.Visible = this.DgvTxtConEconomicStatusVisable;
this.dgvTxtConHardwareStatus.Visible = this.DgvTxtConHardwareStatusVisable;
this.dgvTxtConImpromedAccNum.Visible = this.DgvTxtConImpromedAccNumVisable;
this.dgvTxtConServiceStatus.Visible = this.DgvTxtConServiceStatusVisable;
this.dgvTxtConSoftwareStatus.Visible = this.DgvTxtConSoftwareStatusVisable;
this.dgvCbxConPreProductionId.Visible = this.DgvCbxConPreProductionIdVisable;
this.dgvCbxConProductionId.Visible = this.DgvCbxConProductionVisable;
return new System.Windows.Forms.DataGridViewColumn[] {
this.dgvTxtConAccount,
this.dgvTxtConImpromedAccNum,
this.dgvTxtConCreateDate,
this.dgvTxtConAccuracyStatus,
this.dgvTxtConEconomicStatus,
this.dgvTxtConSoftwareStatus,
this.dgvTxtConServiceStatus,
this.dgvTxtConHardwareStatus,
this.dgvCbxConPreProductionId,
this.dgvCbxConProductionId,
this.dgvTxtCmnHold,
this.dgvTxtCmnConcern,
this.dgvTxtCmnAccuracyStatus,
this.dgvTxtCmnEconomicStatus,
this.dgvTxtCmnSoftwareStatus,
this.dgvTxtCmnServiceStatus,
this.dgvTxtCmnHardwareStatus,
this.dgvTxtCmnAncillaryStatus,
this.dgvTxtCmnFlowStatus,
this.dgvTxtCmnImpromedAccountNum,
this.dgvTxtCmnOpportunityId};
}
The issue is when I check a button the first time, everything shows up ok. I choose another view, everything is ok. But when I click on the first view the columns are out of order (it is like they are in reverse order but it is not exactly the same). this happens only to the first page you click on, the other two are fine. You can click off and click back on as many times as you want after those initial steps, The first list you selected at the start will be out of order the other two will be correct.
Any ideas on what could be causing this?
EDIT--
Things I have found so far:
ColumnDisplayIndexChanged fires many many times (over 200 times) when I view the first selection a second time. if the function does nothing it still loads the page, if i put a dialog box to show it fired (it was a lot of clicks) eventually i either get a big red X in the data grid view area or it loads fine (depending on the page, I get a X for pre-production but the other two loads fine (the message box still shows up hundreds of times) when you select them first)
My best guess is that this.XXX.Fill is changing the DisplayIndex value if the change is occuring after the column range creation function has returned. There are a few things you could consider however.
Create the range of columns once rather than each time a different view is selected.
Is memory an issue? If the datasets are not large and should not be large in the future you could fill 3 seperate containers and change the binding to a different container rather than refilling a single container everytime.
I think I would at the very least create the column ranges only once rather than each time.
Edit
private DataGridViewColumns[] PreProducitonColumns {get;set;}
private DataGridViewColumns[] ProductionColumns {get;set;}
private DataGridViewColumns[] ContractsColumns {get;set;}
private void Form_Load()
{
this.PreProducitonColumns = searchSettings.GetPreProductionColumns();
this.ProductionColumns = searchSettings.GetProductionColumns();
this.ContractsColumns = searchSettings.GetContractsColumns();
}
private void rbContracts_CheckedChanged(object sender, EventArgs e)
{
dgvContracts.Columns.Clear();
if (((RadioButton)sender).Checked == true)
{
if (sender == rbPreProduction)
{
dgvContracts.Columns.AddRange(PreProducitonColumns);
this.contractsBindingSource.DataMember = "Preproduction";
this.preproductionTableAdapter.Fill(this.searchDialogDataSet.Preproduction);
}
else if (sender == rbProduction)
{
dgvContracts.Columns.AddRange(ProductionColumns);
this.contractsBindingSource.DataMember = "Production";
this.productionTableAdapter.Fill(this.searchDialogDataSet.Production);
}
else if (sender == rbContracts)
{
dgvContracts.Columns.AddRange(ContractsColumns);
this.contractsBindingSource.DataMember = "Contracts";
this.contractsTableAdapter.Fill(this.searchDialogDataSet.Contracts);
}
}
}
I took the easy way out. I just created 3 DataGridView and set them visible based off of the radio button.

Categories

Resources