Dropdownlist with datasource set and empty value? - c#

Is there a quick way to add a blank value to a drop down list for a winforms application? Some of my dropdowns are bound to lists of objects and some are bound to datarows from a datatable. Since I am setting the datasource property, I can't just add one through code. Is there any quick way of getting a blank value added or will I have to do it manually for each drop down?

You could add a DataRow with empty values to your datatable programatically,

Here's one I've used to do a blank entry before enum values. Obviously this won't work for more complex binding scenarios.
combo1.DataSource = (new object[] { null }
.Concat(Enum.GetValues(typeof(myEnumType)).Cast<object>()))
.ToList();

Related

Bound ComboBox not matching

I'm new to C# but not to programming. I've been toying around with VS, becoming more comfortable with the language and got stuck on a combobox bound to an int datatable column of an in-memory dataset.
I worked on a DataGridView and had no problems creating a DataGridViewComboBoxColumn and populating its dropdown list using a custom class comprised of Key:int and Desc:string. ValueMember = Key, DisplayMember = Desc. DataSource is left as null since the list is directly built into the ComboBox. Pick from the combobox and save changes works fine in the grid.
Then I moved to a ComboBox. Both the grid and the ComboBox have the exact same BindingSource. So yes they point to the same row at the same time.
I bind the ComboBox with:
cbCtrl.DataBindings.Add( "Text", myBindingSource, ColDBName );
Without populating the dropdown items of the ComboBox, I see the raw int value show up in the ComboBox. I change rows using the grid and the ComboBox value changes too. So it's good.
Then I populate the dropdown list of items in the ComboBox (the same as the grid's column tied to the same column) and it's trouble. The raw int value (eg 19) does not get matched to the proper "Key" item in the dropdown list of the ComboBox. I've tried DropDownStyle = DropDown & DropDownList but no luck with either. And I've looked for hours trying to find a fix. There are no events hooked up to the ComboBox. I expected automatic hookup of the raw value to the matching "Key" item in the ComboBox's dropdown list.
Is there something else to hook up? Frustrating since I expect something minor.
Any help would be Greatly appreciated. Thank you.
*Edit: The dropdown list actually comes from a populated BindingList<> and the BindingList<> is supplied as the ComboBox.DataSource.
I finally stumbled upon the answer:
cbCtrl.DataBindings.Add( "SelectedValue", myBindingSource, ColDBName );
That's all I needed. I got it from a great article
http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial?msg=5325959#xx5325959xx

The selection in the LookUpEdit is not saved

I have in my Grid three columns each one with a LookUpEditor inside. Each one displays different data without any problem.
I have set the property GridView.OptionsBehavior.AutoSelectAllIneditor to true to display an empty row in the bottom to add new data to the grid.
My problem is that when I display the LookUpEditor in my first column and select one item and then move to the next column to select another, data my first column does not maintain it's value, and the same with the other column.
Here is the code I used to set my DataSource in the grid and in the LookUpEdit Repository:
gc_Operaciones.DataSource = _parametroEnsayoProductoList;
repositoryItemLookUpEdit1.DataSource = NBibliography.GetAllElab().Select(p => p.NombreProd).ToList();
repositoryItemLookUpEdit2.DataSource = NBibliography.GetAllTypeEnsayo().Select(p => p.Descripcion).ToList();
repositoryItemLookUpEdit3.DataSource = NBibliography.GetAllEnsayo().Select(p => p.Nombre).ToList();
The reason for this is that the references to your DataSources are being used between the multiple LookUpEdits. This has happened to me before and the best way to avoid this situation is to make sure that the data set that is being passed into the LookUpEdit's DataSource is a new object for each of the LookUpEdits. If you have references to the same data within the multiple LookUpEdits DataSources than the EditValues of the LookUpEdits will change even when you manipulate different LookUpEdits that you have not selected.
Without your code it is difficult for me to code the solution to your issue, but I always just take the data that I need and make sure that I am creating a new copy of the object that I bind to each LookUpEdit's DataSource. This way each LookUpEdit has it's own set of data and when the data is manipulated it will not interfere with the other LookUpEdits data references.

Filtering in datagrid in .net

I have developed a Windows application which has one DataGrid. I am assigning Defaultview of on datatable as datasource to that datagrid.
Then after based on some filter criteria I derived a DataView from the DataGrid 's DataSource and then applying the filter to that view and then assigned that view to grid.
It works perfectly fine.
Now when i again populate that grid with the full set of data on refresh button after clearing data in the DataSource of the grid, the filter condition is not cleared, it still persists.
So only subset of data is being displayed even though I have refreshed.
Please let me know how to clear the rowfilter while refreshing.....
Thanks......
To clear a filter on a DataView, set its RowFilter property to an empty string:
yourDataView.DefaultView.RowFilter = "";
First make the filter criteria to be assigned to a global variable, and on the Click of refresh button event handler, you assign some empty string to that global variable. This will surely solves your problem.

ASP.NET & C# - Two values in a listbox?

I'm adding ListItems to a ListBox from two controls, both are DropDownLists.
The ListItem has the properties ListItem.SelectedItem and ListItem.SelectedValue, but I also want the ListBox to keep track of which DropDownList the ListItem came from.
What would be the best way to do this?
You could set the ID of the dropdown programatically as a attribute of the listitem.
ListItem i = new ListItem();
i.Attributes["IDofDropDown"] = "SomeID";
Encode the .Value section so that its something like DropDownList1:SomeValue and then you can use String.Split to extract the info back out of .SelectedValue?
ListItem item contains Text and Value properties that mapped from option element in HTML. So you can not add any other value to this structure. But maybe you can save the source dropdown's id to the Value of the ListItem.
You could create an in memory dataset to store all the data needed and then bind the dataset to your ListBox. When ever a value is selected you will have access to more fields in code behind.
The way I went about solving this, was creating an ArrayList, with another array inside for each item.

How to remove selected items from ListBox when a DataSource is assigned to it in C#?

How to remove selected items from ListBox when a datasource is assigned to it in C#?
When trying to remove, got error
"Items collection cannot be modified when the DataSource property is set."
But when i try to remove item from datasource (datatable) ,
it thorws error as "datarow is not in current row collection".
Find that item in the DataSource object and remove it, then re-bind the ListBox.
EDIT:
Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
dt.Rows.Remove(rowView.Row);
I haven't tried with anything other than WinForms DataGridViews, but I highly recommend BindingListView, which is both faster than DataTables/Views and allows you to bind generic List<T>s as your DataSource.
Alternatively, use a list that implements IBindingList or inherits from BindingList. When objects are added or removed from a Binding List, any controls bound to it are automatically notified of the change and will update themselves accordingly. If you are using BindingList and your class also implements INotifyProperty changed, Any changes to class properties will also be updated automatically in the databinding control. For example, if a column in a datagrid(view) is bound to a property, "Name", and you change "Name" in the datasource, the datagrid will automatically update. If you add a new item to the datasource, the datagrid will update automatically. Binding List also supports notification in the other direction. If a user edits the "Name" field ina datagrid, the bound object will be updated automatically. Going off topic slightly, if you go a little further and impliment "SupportsSortingCore" and the associated methods in BindingList, you can add automatic sorting to your data. Clicking on a columnm header will automatically sort the list and display the header sort direction arrow.
If the ListBox has a datasource assigned, you must remove items from the datasource and then rebind the ListBox
You need to modify the data source rather than the Items collection of the control. Depending on what kind of data source you are binding to, there are going to be different things you have to do so that your UI updates.
The best way is find a collection that fits your needs and implements IBindingList or IBindingListView. Those two interfaces implement even handlers that listen for a CollectionChanged event and update your UI accordingly.
If your collection doesn't support those interfaces, you're going to have to re-bind your data source every time somebody adds/removes an item.
when you get the message "Items collection cannot be modified when the DataSource property is set."
setting the datasource to something else, empty list or null does not help when
the code initializecomponent is not completed.
to avoid that error, one must do the change of datasource or the item list during or after form load.
I know it does not seem to make sense. Hoever, the visual studio designer will generate code in the form designer.cs or vb that will add items to the listbox if any code that changes the items is found before end of initialize components
While Chris Doggett posted a valid solution, I ran into problems while using it. By using that method it was not allowing a subsequent GetChanges(DataRowState.Deleted) to work properly.
To better solve my problem, I only had to change a single line - the last line.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
rowView.Row.Delete();
This allowed my GetChanges call to work properly.
This worked for me
DataTable temp = (DataTable)lstBlocks.DataSource;
temp.Rows.RemoveAt(position);
its vary simple , assign a new blank value to listbox
eg..
Dim ABC As New List(Of String)()
ListBox1.DataSource = ABC
ListBox implementation is bugged, you need to create a new data source instance for the component for it to recognize a change.
Eg:
ActivitiesList.DataSource = _activities;
_activities = new List<Activity>(_activities);
_activities.Remove((Activity)ActivitiesList.SelectedItem);
ActivitiesList.DataSource = _activities;

Categories