ListBox DataSource assignment - c#

I have here a desktop application with ListBox that will accept records (files inside a directory and its sub-directories) of more than 10,000. When I assign its DataSource with that DataTable of more than maybe 50,000 it makes the UI hang even though it is inside the DoWork of a BackgroundWorker, thus, hangs also my ProgressBar that indicates the progress of the assignment of data in the ListBox.
I have also used the method here to avoid cross threading while assigning its DisplayMember and ValueMember but still it gets hang.
Here's the code:
private void bgWorkerForLstBox1_DoWork(object sender, DoWorkEventArgs e)
{
string viewPath = string.Empty;
if (radFullPath.Checked)
viewPath = "fullPath";
else if (radShortPath.Checked)
viewPath = "truncatedPath";
else
viewPath = "fileName";
if (dt1 != null)
if (dt1.Rows.Count > 0)
SetListBox1Props(viewPath, "fullPath");
}
delegate void SetListBox1PropsCallback(string DisplayMember, string ValueMember);
private void SetListBox1Props(string DisplayMember, string ValueMember)
{
if (this.lstBox1.InvokeRequired)
{
SetListBox1PropsCallback d = new SetListBox1PropsCallback(SetListBox1Props);
this.Invoke(d, new object[] { DisplayMember, ValueMember });
}
else
{
this.lstBox1.DataSource = dt1;
this.lstBox1.DisplayMember = DisplayMember;
this.lstBox1.ValueMember = ValueMember;
}
}

The number of items you want to show is too large for windows. If you need this and don't want to implement some sort of pagination, i would suggest to use a ListView control in VirtualMode. See this link for more information: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx

Related

A self-learning C# DataGridView Combobox?

I would like to have a column of ComboBoxes in a DataGridView, which allows the user to freely input some text, which is collected in the dropdown menus, so that entering the same text in the next box is faster. I'd prefer not to use DataGridViewComboBoxColumn, unless I really have to.
The following code nearly does the job but has these issues:
After entering some new text and hitting return, the newly entered text is immediately replaced with the old value
But the new text is successfully added to the dropdown menus of all of the comboboxes
when I select this newly added text in one of the boxes, I get DataGridView-Exceptions complaining about an invalid value.
It seems the boxes somehow have for validation purposes a copy of the datasource which doesn't get updated?
public partial class Form1 : Form
{
List<string> data = new List<string>(); // shared data source for all ComboBoxes
private void checkData(string s) // check wether s in the list, add it if not, keep things sorted
{
if (data.Contains(s))
return;
data.Add(s);
data.Sort();
}
private void addCell(string s) // add a new cell to the grid
{
checkData(s);
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.DataSource = data;
c.Value = s;
int i = theGrid.Rows.Add();
theGrid.Rows[i].Cells[0] = c;
}
public Form1()
{
InitializeComponent();
theGrid.ColumnCount = 1;
addCell("Foo");
addCell("Bar");
}
// handler to enable the user to enter free text
private void theGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
cb.DropDownStyle = ComboBoxStyle.DropDown;
}
// handler which adds the entered text to the data source
private void theGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
checkData(e.FormattedValue.ToString());
}
}
After some tests, I am guessing that the individual combo boxes are not getting updated as you think they are. It appears that in the checkData method, that the data is updated with a new s. This will visually update the combo box cell, however the DataSource for each of the combos needs to be updated. Hence the DataError exception when the new added value is selected.
Considering that each combo box cell is “independent” and not part of a DataGridViewComboBoxColumn… then a loop through all the rows is necessary to update each combo box cell. I am not sure why a DataGridViewComboBoxColumn would not be used here.
private void checkData(string s) // check wether s in the list, add it if not, keep things sorted
{
if (data.Contains(s))
return;
data.Add(s);
data.Sort();
// now because each cell is independent... we have to update each data source!
UpdateCombos();
}
private void UpdateCombos() {
foreach (DataGridViewRow row in theGrid.Rows) {
if ((!row.IsNewRow) && (row.Cells[0].Value != null)) {
string currentValue = row.Cells[0].Value.ToString();
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.Value = currentValue;
c.DataSource = data;
row.Cells[0] = c;
}
}
}
Using the posted code, A call to UpdateCombos is added to the checkData method. This method as expected loops through all the rows in the grid and replaces each combo box with the updated data. I will not disagree that it may be prudent to replace the data source, however I would use a combo box column, which the code below does. With this change, the UpdateCombos is not needed and simply update the combo box column.
The DataGridViewComboBoxColumn is exposed since the data source is updated frequently.
private List<string> comboData;
private DataGridViewComboBoxColumn comboColumn;
private void Form2_Load(object sender, EventArgs e) {
comboData = new List<string>();
comboData.Add("Foo");
comboData.Add("Bar");
comboColumn = new DataGridViewComboBoxColumn();
comboColumn.DataSource = comboData;
theGrid2.Columns.Add(comboColumn);
theGrid2.RowCount = 3;
}
private void checkData2(string s) {
if (!comboData.Contains(s)) {
comboData.Add(s);
comboData.Sort();
comboColumn.DataSource = null;
comboColumn.DataSource = comboData;
}
}
Hope that helps

Updating the existing DataGridViewComboBoxColumn Items collection

We have DataGridViewComboBoxColumn in which we have four values which are fixed. During run-time when the event dataGridView1_EditingControlShowing occurs we are trying to append new items to DataGridViewComboBoxColumn.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.DropDown += new System.EventHandler(ComboBox1_DropDown);
}
}
private void ComboBox1_DropDown(object sender, System.EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
if (comboBox.Items != null)
{
List<String> elementname = Elements();
foreach (string s in elementname)
{
if (!comboBox.Items.Contains(s))
{
comboBox.Items.Add(s);
}
}
}
}
I am getting this exception :
Can you please suggest how to add the values to the existing DataGridViewComboBoxColumn in Items collection.
You are adding into the Items of editing control but not into the Items of the ComboBoxColumn, which will eventually be used for validation.
To get easy access to the hosting DGV we use the special type DataGridViewComboBoxEditingControl.
Now we will add the new choices to both Items collections now in the ComboBox1_DropDown event: :
DataGridViewComboBoxEditingControl comboBox = (DataGridViewComboBoxEditingControl)sender;
DataGridView dgv = comboBox.EditingControlDataGridView;
if (comboBox.Items != null && dgv != null)
{
DataGridViewComboBoxColumn dcbc =
(DataGridViewComboBoxColumn) dgv.Columns[dgv .CurrentCell.ColumnIndex];
List<String> elementname = Elements.ToList();
foreach (string s in elementname)
{
if (!comboBox.Items.Contains(s))
{
comboBox.Items.Add(s);
dcbc.Items.Add(s);
}
}
}
Note:
The new Items will not be persistet unless you code for it.
So if you have set fields to new values and saved them, you must also save and reload those new values before re-loading the DGV or else the values will not be in the Column's list of values and throw the DataError again!
The usual place to store them would be a DataTable in your DBMS, but any other external storage may also be used like an XML file or maybe dynamic resources etc.. But the DBMS is the most natural choice imo.

ComboBox.SelectedValue not working as expected

So I have a DataGridView which I am using as a “row selector” on a form, and a bunch of controls are bound to the bindingSource.
One of the bound controls is a ComboBox serving as a lookup which enables status choices for the rows, this is populated from a DataTable with data pulled from the DB.
The population of this box is without any issue.
When a given row is selected from the DGV the form controls display data from the given row as they should, however the “statusComboBox” is not quite playing the game.
If in the DGV, I choose a row that has a different status to one previously selected, it works as it should, however, if I choose a row with the same value to a previously selected row, instead of the box showing the DisplayMember it shows the ValueMember.
IT only seems to occur in the above scenario, where the rows selection only instigates a display response from the bound ComboBox providng a previous selection had a different “Status ID”. What have I dont wrong that would cause this behaviour?
So the form load looks like this
private void ProjectsForm_Load(object sender, EventArgs e)
{
InitBindingSource();
//// bind Selector
//ASMod$ this needs to be 'true' unless you explicitly declare columns
ProjectsDataGridView.AutoGenerateColumns = false;
ProjectsDataGridView.DataSource = ProjectsBindingSource;
GetData();
//Set GeneralStatusBox
Helpers.GeneralStatusInitLookup(statusComboBox, ProjectsBindingSource);
}
The ProjectBindingSource is initialised thus:
private void InitBindingSource()
{
ProjectsBindingSource = new BindingSource();
projectsBindingNavigator.BindingSource = ProjectsBindingSource;
ProjectsBindingSource.PositionChanged += new EventHandler(ProjectsBindingSource_PositionChanged);
}
A ProjectsAddDataBindings procedure, and the contained DataBindings.Add for the ComboBox (executed at the end of a GetData routine that additionally populated ProjectsBindingSource):
ProjectsAddDataBindings();
{
…
this.statusComboBox.DataBindings.Add("Text", ProjectsBindingSource, "GSID");
…
}
After the GetData block the GeneralStatusInitLookup populates the Lookup elements, in a helper class simply because it provides functionality to a number of different forms
public static void GeneralStatusInitLookup(System.Windows.Forms.ComboBox comboBox, BindingSource primaryBindingSource)
{
string statusFilter = "";
statusFilter = Helpers.GetStatusGroupFilter(EndeavourForm.FilterId);
if (statusFilter != "")
{
statusFilter = " WHERE " + statusFilter;
}
//// string statusFilter = ""; //// temp
string sql = "";
sql = "SELECT GSID, ShortName FROM GeneralStatus" + statusFilter + " ORDER BY Pos";
GeneralStatusDataTable = Helpers.Db.GetDataTable(sql);
comboBox.DataSource = GeneralStatusDataTable;
comboBox.DisplayMember = "ShortName";
comboBox.ValueMember = "GSID";
comboBox.DataBindings.Add(new Binding("SelectedValue", primaryBindingSource.DataSource, "GSID"));
}
And the DGV initiated row change is handled like this
private void ProjectsBindingSource_PositionChanged(object sender, EventArgs e)
{
try
{
// Update the database with the user's changes.
UpdateProjects();
statusComboBox.SelectedValue = (int)CurrentDataRowView.Row["GSID"];
}
catch (Exception)
{
}
}
private void UpdateProjects()
{
try
{
ProjectsDataAdapter.Update((DataTable)ProjectsBindingSource.DataSource);
DataHelper.CommitProposedChanges(projectsDataSet);
if (this.projectsDataSet.HasChanges() == true)
{
ProjectsBindingSource.EndEdit();
ProjectsDataAdapter.Update();
}
CurrentDataRowView = (DataRowView)ProjectsBindingSource.Current;
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception)
{
throw;
}
}
Anyway I hope I haven't swamped readers with to much code, but frankly I cant see where this is going wrong. So any help would be greatly appreciated.
This was a simple solution in the end. Both the GeneralStatusInitLookup() and the ProjectsAddDataBindings() blocks made use of DataBindings.Add ... For the lookup table this was fine, but with the binding to the main table; the later, I had used "Text" as the propertyName parameter.

How to create an Auto-complete combo-box or text box to filter text containing a string

How do I create an Auto-complete ComboBox or TextBox that filters text based on a string?
For example: if I type an "a" in a TextBox, I only get to see all strings containing an "a".
If you mean show suggestions then it's a simple matter of changing a property when you have the TextBox selected in your IDE of choice:
The options shown in the picture allow you to change the rules for autocompleting text in the text box as well as the source for the suggestions. (Visual Studio 2010)
You can go to the following link to learn more about the TextBox control.
MSDN Text Box Control
Windows Forms's autocomplete implementation uses Shell's autocomplete object, which can only do a "BeginWith" match until Windows Vista.
If you can demand your users to upgrade to Windows Vista, you can use IAutoComplete2::SetOptions to specify ACO_NOPREFIXFILTERING. Otherwise I am afraid you need to write your own.
Here is how I auto-complete for a specific value in a comboDropDown box.
void comboBox_Leave(object sender, EventArgs e)
{
ComboBox cbo = (sender as ComboBox);
if (cbo.Text.Length > 0)
{
Int32 rowIndex = cbo.FindString(cbo.Text.Trim());
if (rowIndex != -1)
{
cbo.SelectedIndex = rowIndex;
}
else
{
cbo.SelectedIndex = -1;
}
}
else
{
cbo.SelectedIndex = -1;
}
}
This filters results based on user input. Optimizing for large lists, populating your own data and error handling left out for you to complete:
public partial class Form1 : Form
{
List<String> data;
ListView lst = new ListView();
TextBox txt = new TextBox();
public Form1()
{
InitializeComponent();
data = new List<string>("Lorem ipsum dolor sit amet consectetur adipiscing elit Suspendisse vel".Split());
}
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(txt);
lst.Top = 20;
txt.TextChanged += new EventHandler(txt_TextChanged);
lst.View = View.List;
this.Controls.Add(lst);
list_items("");
}
void txt_TextChanged(object sender, EventArgs e)
{
list_items(txt.Text);
}
void list_items(string filter)
{
lst.Items.Clear();
List<string> results = (from d in data where d.Contains(filter) select d).ToList();
foreach (string s in results)
{
lst.Items.Add(s);
}
}
}
To get the combobox to auto complete, set the AutoCompleteSource and AutoCompleteMode properties:
cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
The ListItems source tells the combo to use it's items collection as the auto complete source.
I know this is an old topic but i tried so hard to find a solution for c# autocomplete filtering too and couldn't find any so i came up with my own simple and easy way so i'll just share it for those who may think it's useful and wanna use in their projects. It does not use the control's autocomplete features. What it does just simply get the text entered from the combobox, search it in the source then display only the matching ones from the source as the combobox' new source. I implemented it in the combobox' KeyUp event.
Let's say (actually this is what i do for almost all the cases when i want autocompleting) we have a globally assigned DataTable called dt_source to be the combobox' source and it has two columns: id(int) and name(string).
DataTable dt_source = new DataTable("table");
dt_source.Columns.Add("id", typeof(int));
dt_source.Columns.Add("name", typeof(string));
And this is what my KeyUp method looks like:
private void cmb_box_KeyUp(object sender, KeyEventArgs e)
{
string srch = cmb_box.Text;
string srch_str = "ABackCDeleteEFGHIJKLMNOPQRSpaceTUVWXYZD1D2D3D4D5D6D7D8D9D0";
if (srch_str.IndexOf(e.KeyCode.ToString()) >= 0)
{
cmb_box.DisplayMember = "name"; // we want name list in the datatable to be shown
cmb_box.ValueMember = "id"; // we want id field in the datatable to be the value
DataView dv_source = new DataView(dt_source); // make a DataView from DataTable so ...
dv_source.RowFilter = "name LIKE '%"+ srch +"%'"; // ... we can filter it
cmb_box.DataSource = dv_source; // append this DataView as a new source to the combobox
/* The 3 lines below is the tricky part. If you repopulate a combobox, the first
item in it will be automatically selected so let's unselect it*/
cmb_box.SelectedIndex = -1; // unselection
/* Again when a combobox repopulated the text region will be reset but we have the
srch variable to rewrite what's written before */
cmb_box.Text = srch;
/* And since we're rewriting the text region let's make the cursor appear at the
end of the text - assuming 100 chars is enough*/
cmb_box.Select(100,0);
cmb_box.DroppedDown = true; // Showing the dropdownlist
}
}
I think your best bet is to override the OnKeyDown(KeyEventArgs e) event, and use the value to filter the ComboBox.AutoCompleteCustomSource. Then as noted above, change the AutoCompleteSource to AutoCompleteSource.ListItems.

Comboboxes only load when selecting the second items and below

This is really strange. I want to select a State and load Cities from that State in another combobox.
It's working EXCEPT when selecting the first item in the combobox:
Here's my entire class. The if statement in the selectedIndexChanged is to make sure that something is selected. The problem is that if I set that to cmbState.SelectedIndex >= 0 then an exception is raised because on initial load the comboBox doesn't has a .State variable there and not a .Value.
I don't know if this makes any sense.
private void MainForm_Load(object sender, EventArgs e)
{
LoadDepartmentsToComboBox();
}
private void LoadCitiesToComboBox(long StateID)
{
cmbCity.DataSource = null;
CityRepository cityRepo = new CityRepository();
cmbCity.DataSource = cityRepo.FindAllCities().Where(c => c.IDState == StateID);
cmbCity.DisplayMember = "Name";
cmbCity.ValueMember = "ID";
}
private void LoadDepartmentsToComboBox()
{
cmbState.DataSource = null;
StateRepository stateRepo = new StateRepository();
cmbState.DataSource = stateRepo.FindAllStates();
cmbState.DisplayMember = "Name";
cmbState.ValueMember = "ID";
}
private void cmbState_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbState.SelectedIndex > 0)
{
LoadCitiesToComboBox(Convert.ToInt64(cmbState.SelectedValue));
}
}
If I do use cmbState.SelectedIndex >= 0 then I receive this exception:
Unable to cast object of type
'DocumentScannerDanyly.State' to type
'System.IConvertible'.'System.IConvertible'.
When I don't use the SelectedIndex >= 0 and use plain old >0 then everything works except when selected the first item, which does nothing; understandably because it doesn't take the first item into account.
Thanks a lot for the help.
Don't assign the Display member & the Value member in each load, just assign them once in constructor for example.
add ToList() to the result which will assign to DataSource,
Complex DataBinding accepts as a data source either an IList or an IListSource.
check this.

Categories

Resources