I have a combobox binded to a list like this
public List<CustomerLanguage> CurrentCustomerLanguageList
{
get { return _currentCustomerLanguageList; }
set
{
_currentCustomerLanguageList = value;
bsCustomerLanguages.DataSource = Presenter.CustomerLanguageToProxy(value);
cbLanguage.DataSource = bsCustomerLanguages.DataSource;
cbLanguage.DisplayMember = "LanguageName";
cbLanguage.ValueMember = "Id";
}
}
On the form i have + - buttons which must allow to add or delete items inside combobox.
The problem is: i dont know how to add new item to binding source and the list without full refresh of combobox.
Of course when i add, selected value must remains and no selectedvaluechanged event must be raised.
'bsCustomerLanguages' is a BindingSource ? In that case it should work if you set cbLanguage.DataSource = bsCustomerLanguages and add to bsCustomerLanguages directly
Related
I have a databound combobox:
using(DataContext db = new DataContext())
{
var ds = db.Managers.Select(q=> new { q.ManagerName, q.ManagerID});
cmbbx_Managers.BindingContext = new BindingContext();
cmbbx_Managers.DataSource = ds;
cmbbx_Managers.DisplayMember = "ManagerName";
cmbbx_Managers.ValueMember = "ManagerID";
}
When the form loads neither item is selected, but when the user chooses an item it cannot be deselected. I tried to add cmbbx_Managers.items.Insert(0, "none"), but it does not solve the problem, because it is impossible to add a new item to the databound combobox.
How do I allow a user to deselect a combobox item?
To add an item to your databound ComboBox, you need to add your item to your list which is being bound to your ComboBox.
var managers = managerRepository.GetAll();
managers.Insert(0, new Manager() { ManagerID = 0, ManagerName = "(None)");
managersComboBox.DisplayMember = "ManagerName";
managersComboBox.ValueMember = "ManagerID";
managersComboBox.DataSource = managers;
So, to deselect, you now simply need to set the ComboBox.SelectedIndex = 0, or else, use the BindingSource.CurrencyManager.
Also, one needs to set the DataSource property in last line per this precision brought to us by #RamonAroujo from his comment. I updated my answer accordingly.
The way you "deselect" an item in a drop-down ComboBox is by selecting a different item.
There is no "deselect" option for a ComboBox—something always has to be selected. If you want to simulate the behavior where nothing is selected, you'll need to add a <none> item (or equivalent) to the ComboBox. The user can then select this option when they want to "deselect".
It is poor design that, by default, a ComboBox appears without any item selected, since the user can never recreate that state. You should never allow this to happen. In the control's (or parent form's) initializer, always set the ComboBox to a default value.
If you really need a widget that allows clearing the current selection, then you should use a ListView or ListBox control instead.
To deselect an item suppose the user presses the Esc key, you could subscribe to the comboxBox KeyDown event and set selected index to none.
private void cmbbx_Managers_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape && !this.cmbbx_Managers.DroppedDown)
{
this.cmbbx_Managers.SelectedIndex = -1;
}
}
I have a ComboBox bound to an ObservableCollection of tbPublications which populates as it should. I then select a row from a DataGrid which fires another Create form in which I insert a new record into tbPublications, all good.
When I close said create form and return to my ComboBox form I am clearing and re-reading in the one new item to my ObservableCollection, returning the user to the item they've just created. The ComboBox then displays the one item from my newly populated collection, all good.
My problem is that on returning to my ComboBox form, the new publication is not set as selected item in the ComboBox display, the user has to click the ComboBox then select the item.
I can't use SelectedIndex = "0" in my view XAML as I want to show the whole ObservableCollection in my ComboBox on page load.
Is there any way to use a method in the ViewModel maybe to solve this issue, something maybe such as..
private void SetSelectedIndex()
{
if (MyObservableCollection.Count == 1)
{
//Set selected indexer to "0";
}
}
Found a solution to this, not sure if it's the cleanest 'MVVM' solution...
After reading in my ObservableCollection I invoke this method:
if (_ModelPublicationsObservableList.Count == 1)
{
SelectedPublication = _ModelPublication;
SetSelectedIndex();
}
Here's the method which gets the current main window and sets the SelectedIndex:
private void SetSelectedIndex()
{
ArticlesDataGridWindow singleOrDefault = (ComboBoxWindow)Application.Current.Windows.OfType<ComboBoxWindow>().SingleOrDefault(x => x.IsLoaded);
singleOrDefault.comboBox1.SelectedIndex = 0;
}
Did you consider using the SelectedItem property of combobox? You can bind the selected item property of combobox to get or set the selected item.
XAML
<ComboBox ItemsSource="{Binding Path=Publications}" SelectedItem="{Binding Path=SelectedPublication, Mode=TwoWay}" />
ViewModel
public class ItemListViewModel
{
public ObservableCollection<Publication> Publications {get; set;}
private Publication _selectedPublication;
public Publication SelectedPublication
{
get { return _selectedPublication; }
set
{
if (_selectedPublication== value) return;
_selectedPublication= value;
RaisePropertyChanged("SelectedPublication");
}
}
}
If you want to set the selected item from View model,You can set the SelectedPublication property as-
SelectedPublication = Publications[0];
Or you can locate the required item in the Publications collection and assign it to SelectedPublication property.
Add UpdateSourceTrigger=PropertyChanged to your binding.
SelectedItem={Binding Path=SelectedPublication, Mode=TwoWay}, UpdateSourceTrigger=PropertyChanged}
I am developing an WPF application. It is having a DataGrid in it. I have assigned the ItemSource of my datagrid to an IEnumerable collection.
I have a Treeview in my window. When I click the element in the treeview it has to load the datagrid
private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
this.dataGrid1.ItemsSource = null;
this.dataGrid1.Visibility = Visibility.Visible;
this.dataGrid1.ItemsSource = objref.FinalValue;
// Where Objref.FinalValue is an IEnumerable collection.
grid_data = objref.FinalValue;
}
But the problem is everytime the selection is changed, the values in the datagrid is not overwrittenen but it is appended. I flushed the datagrid with dataGrid1.Columns.Clear() and dataGrid.ItemSource = null; Later I found out that the objref.FinalValue is appended. So even though I flushed the datagrid it displays the entire value..
So in the class which is having objref as instance I have used
private IEnumerable Result;
public IEnumerable FinalValue
{
get { return Result; }
set { Result = value; }
}
// Update Result with values so that it can be assigned to datagrid.
I need to overwrite not append. But the FinalValue has been appended every time. How can I resolve this issue?
Whenever you update the ItemsSource after the grid is rendered you have to call dataGrid1.Items.Refresh() to update it. After calling Refresh() the datagrid rows will reflect the new collection that is bound to it.
When I databind my GridView to an ObservableCollection, the first item of the collection is automatically selected. The SelectionMode property of the GridView is set to multiple. Is there some way to prevent this auto-selection? Or on what event should I listen so that I can reset the SelectedIndex of the GridView back to -1?
Set the IsSynchronizedWithCurrenItem property to false on the gridview in xaml
There is acutally a pretty simple solution. I set the SelectionMode of the GridView to None in the XAML. Then, when the page is created, I change the SelectionMode to Multiple.
publicPage()
{
this.InitializeComponent();
itemListView.SelectionMode = ListViewSelectionMode.Multiple;
}
However, the problem I am having seems to be caused by my own program. This is a workaround for the issue I am having, the autoselection is not the default behavior.
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/da7e9f3b-9a3e-47ca-8223-b50539293f5f
My situation is the opposite. I have a GridView that was bind to an ObservableCollection, and I wanted the 1st item to be selected but it was not! I figured out why that was the case though. There are 2 ways to generate my ObservableCollection and depending on which method I chose, the 1st item is either selected or not.
for example, I have a variable ItemList in my viewmodel which I bind to my GridView
public ObservableCollection<Item> ItemList { get; private set; }
Method 1 (nothing selected)
public void getData()
{
var myList = // get your list here
for (int i = 0; i < myList.Count; i++)
{
this.ItemList.add(myList[i]);
}
}
Method 2 (1st item automatically selected)
public void getData()
{
var myList = // get your list here
this.ItemList = myList
}
I have a combobox control on form that pull its data (Displays and values) from some datasource. On another side I have table with one row. I want when app is lauching, combobox set selectedvalue or selecteditem to value of one column in above row. And when user has changed combobox it will persist change to row. I have tried to bind SelectedValue to this column, but it doesn't work. Combobox just sets on start to first item. What is problem?
EDIT
This is a Win Forms project.
Here is the binding code:
this.comboBoxCountries = new System.Windows.Forms.ComboBox();
this.countriesBindingSource = new System.Windows.Forms.BindingSource(this.components);
//
// comboBoxCountries
//
this.comboBoxCountries.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.searchCriteriaBindingSource, "Postcode", true));
this.comboBoxCountries.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.searchCriteriaBindingSource, "CountryCode", true));
this.comboBoxCountries.DataSource = this.countriesBindingSource;
this.comboBoxCountries.DisplayMember = "Name";
this.comboBoxCountries.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxCountries.FormattingEnabled = true;
this.comboBoxCountries.Location = new System.Drawing.Point(190, 19);
this.comboBoxCountries.Name = "comboBoxCountries";
this.comboBoxCountries.Size = new System.Drawing.Size(156, 21);
this.comboBoxCountries.TabIndex = 2;
this.comboBoxCountries.ValueMember = "Code";
this.comboBoxCountries.SelectedValueChanged += new System.EventHandler(this.comboBoxCountries_SelectedValueChanged);
//
// countriesBindingSource
//
this.countriesBindingSource.DataMember = "Countries";
this.countriesBindingSource.DataSource = this.dbDataSetCountries;
//
// dbDataSetCountries
//
this.dbDataSetCountries.DataSetName = "dbDataSetCountries";
this.dbDataSetCountries.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// searchCriteriaBindingSource
//
this.searchCriteriaBindingSource.AllowNew = false;
this.searchCriteriaBindingSource.DataMember = "SearchCriteria";
this.searchCriteriaBindingSource.DataSource = this.dbDataSetSearchCriteria;
this.searchCriteriaBindingSource.BindingComplete += new System.Windows.Forms.BindingCompleteEventHandler(this.searchCriteriaBindingSource_BindingComplete);
//
// dbDataSetSearchCriteria
//
this.dbDataSetSearchCriteria.DataSetName = "dbDataSetSearchCriteria";
this.dbDataSetSearchCriteria.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
EDIT2
As I have mentioned in my comment below, I have another textbox that is binded to another DataMember of same binding source and textbox working fine. It's appear with appropriate value. When I change DataMember on same datamember on which I set selectedvalue property of combobox binding it's also show a good result and work properly.
Thanks in advance!
Take a look at the DisplayMember and ValueMember properties of the combobox. You need to tell the ComboBox what member from the datasource to display in the drop down, and what value to give when SelectedValue is requested.
It sounds like your ComboBox is bound to a static list while your rows are not. You might consider using a BindingSource that you set the ComboBox and the DataGridView's DataSource to. That way when the DGV navigates to a new row, the ComboBox will be updated with the value for the new row.
Here is a link to the ComboBox on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.aspx
I find it out. So for managing with this issue you should remove SelectedValue databinding from visual studio data bound menu and put an appropriate code to add this databinding in some place after filling all bindingsources:
private void MainForm_Load_1(object sender, EventArgs e)
{
this.searchCriteriaTableAdapter1.Fill(this.dbDataSetCountries.SearchCriteria);
this.searchCriteriaTableAdapter.Fill(this.dbDataSetSearchCriteria.SearchCriteria);
comboBoxCountries.DataBindings.Add("SelectedValue", this.dbDataSetCountries.SearchCriteria, "CountryCode");
}