How to use DataGridComboBoxColumn? - c#

I created a DataGrid and added a DataGridComboBoxColumn programmatically.
public partial class MainWindow : Window
{
private DataGridComboBoxColumn weightColumnChar = new DataGridComboBoxColumn();
ObservableCollection<int> mComboBoxValues;
public ObservableCollection<int> ComboBoxValues
{
get { return this.mComboBoxValues; }
set { this.mComboBoxValues = value; }
}//end property
public MainWindow()
{
InitializeComponent();
mComboBoxValues = new ObservableCollection<int>() {-1, 0, 1 };
}//end constructor
private void Window_Loaded(object sender, RoutedEventArgs e)
{
weightColumnChar.Header = "Weight";
dataGrid_Char.Columns.Add(weightColumnChar);
weightColumnChar.ItemsSource = ComboBoxValues;
Binding binding = new Binding();
binding.Path = new PropertyPath(ComboBoxValues[1]);
weightColumnChar.SelectedItemBinding = binding;
}//end method
private void dataGrid_Char_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}//end method
//Opens ComboBox on first click
private void dataGrid_Char_GotFocus(object sender, RoutedEventArgs e)
{
if (e.OriginalSource.GetType() == typeof(DataGridCell))
{
DataGrid grd = (DataGrid)sender;
grd.BeginEdit(e);
}//end if
}//end method
}//end class
I added an ItemsSource to it and retrieve the values from an ObservableCollection.
The values from the collection are shown in runtime.
My problem is that if I select a value from the ComboBox this vlaue isn't selected and displayed afterwards. What am I doing wrong?
And I also want to select a default value. How does that work?
Please explain programmatically and not in XAML!
Would be great if anybody could help me.
Thanks!!!

First of all you haven't shown what your underlying collection is that is bound to the DataGrid.
You'll need something like DataGrid.ItemsSource = new ObservableCollection<MyClass>(); (it has to be a collection that supports change notification, thus I chose ObservableCollection).
Secondly you are binding the ComboBox.SelectedItemBinding to the ComboBox.ItemsSource which is nonsense. ComboBox.ItemsSource is the collection of values you can choose from, ComboBox.SelectedItemBinding (I would actually use ComboBox.SelectedValueBinding) is the "path" to the underlying data source that contains/reprsents the final value (eg. MyClass.IntProperty). So you select a value from a collection and assign that to some data item (you cannot assign it back to the collection where you select from).
PS! In case you later use something that resembles a KeyValuePair (eg. Id; Name) as your ComboBox.ItemsSource, then you set ComboBox.SelectedValuePath = Id; ComboBox.DisplayMemberPath = Name;. MyClass.IntProperty would contain the Id value in such a case.

Related

BindingSource AddNew() and initializing values

i have a ComponentOne FlexGrid bound to a bindingsource and the bindingsource is bound to a bindinglist collection.
The user clicks an insert button. I call AddNew() on the BindingSource. in the AddingNew() event, i want to initialize the properties in the bindingsource. usually if i want to access the data underlying the grid row i do this
MemberSkill skill = (MemberSkill)MemberSkillBS.Current
skill.SocSecNo = currentMember.SocSecNo;
but when i do this in the AddingNew() event, Current is still pointing to the row with the focus on the grid. how can i access the new item i added to the binding source and initialize it?
The new item becomes the current item after the AddNew has been called.
In your Insert button handler you do:
private void buttonInsert_Click(object sender, EventArgs e)
{
MemberSkill newItem = MemberSkillBS.AddNew() as MemberSkill;
if (newItem != null)
{
MemberSkillBS.Add(newItem);
}
...
}
and in your AddingNew handler you do:
private void MemberSkillBS_AddingNew(object sender, AddingNewEventArgs e)
{
MemberSkill skill = new MemberSkill
{
SocSecNo = MemberSkillBS.Current.SocSecNo
};
e.NewObject = skill;
}

ComboBox behaving in a not expected way

I have two comboboxes which I populate using my GetAllCities() method in the CtrlMap.
My idea is, whenever I select another city on the ddFrom it should databind all the cities to ddTo (and later on remove the exact same selected, so user won't be able to select same city as point From and To).
However, Whenever I select something on ddFrom, ddTo populates (as it should), but SelectedIndex gets the same as the ddFrom. Same goes in the opposite way. If I select a city, lets say New York on ddTo it is also selected on ddFrom.
In the GUINewBooking.Designer.cs there's only this event handler registered: this.ddFrom.SelectedIndexChanged += new System.EventHandler(this.ddFrom_SelectedIndexChanged);
ddTo has no event handler registered. Any ideas?
public partial class GUINewBooking : Form
{
private CtrlMap ctrlMap;
public GUINewBooking()
{
InitializeComponent();
ctrlMap = new CtrlMap();
ddFrom.DataSource = ctrlMap.GetAllCities();
ddFrom.DisplayMember = "name";
}
private void ddFrom_SelectedIndexChanged(object sender, EventArgs e)
{
ddTo.DataSource = ctrlMap.GetAllCities();
ddTo.DisplayMember = "name";
}
}
I believe it's because you are using the same data source. You might need to
private void ddFrom_SelectedIndexChanged(object sender, EventArgs e)
{
CtrlMap ctrlMapTo = new CtrlMap();
ddTo.DataSource = ctrlMap2.GetAllCities();
ddTo.DisplayMember = "name";
}
The answer can be found Strange behavior of Windows Forms combobox control
Each combobox DataSource property should be assigned to a different BindingSource object.
Example:
cmbDataType1.DataSource = new BindingSource(datasource, "");
cmbDataType2.DataSource = new BindingSource(datasource, "");
Or in my particular case:
ddFrom.DataSource = new BindingSource(ctrlMap.GetAllCities(), "");
ddTo.DataSource = new BindingSource(ctrlMap.GetAllCities(), "");

My combobox returns incorrect text value

public void DD_Location()
{
var ctx = new LCCDB_EF();
var query = ctx.tbl_Location;
CB_Location.DataContext = query.ToList();
}
private void CB_Location_DropDownClosed(object sender, EventArgs e)
{
textbox_test.Text =CB_Location.Text;
}
Output in Textbox
System.Data.Entity.DynamicProxies.Location_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6
Try this
if(null != CB_Location.SelectedItem)
textbox_test.Text = CB_Location.SelectedItem.ToString();
Without seeing your XAML I can't be sure, but are you sure you've bound the list correctly? Try setting the Items property of combobox to your list, rather than the data context. Depending on what the type is and what you'd like to bind the text to, you may need to set the DisplayMemberPath property as appropriate, too.

access to property on selection winforms combobox

One article has Name and Price properties. I use Name property to display articles inside combobox cmbDataList like this
public Form1()
{
InitializeComponent();
cmbDataList.DataSource = GetData();
cmbDataList.DisplayMember = "Name";
}
After user selected the preffered article I want to use it's Price property to assign to textbox on the same form. So, how to access to that Price property?
private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
//var sel = cmbDataList.SelectedItem;
}
You have to cast SelectedItem to proper object.
private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
var sel = (YourObject)cmbDataList.SelectedItem;
txt.Text = sel.Price.ToString();
}
Unless all names are unique, you're going to need a unique identifier to reference, for example an articleID.
From here, set the ComboBox's ValueMember like so;
cmbDataList.ValueMember = "ID";
then you can get your value on the event handler;
private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
var sel = cmbDataList.SelectedValue;
//From here you're going to need to find your article with that particular ID.
}
Alternatively. You could have your DisplayMember as the article name, and the price as the ValueMember, then get it in the event handler for SelectedIndexChanged in the same way i put above. SelectedValue will then return the price;
cmbDataList.ValueMember = "Price";
private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
var yourSelectedPrice = cmbDataList.SelectedValue;
}
Assuming GetData() returns a table, you need to write the ValueMember also... like this:
InitializeComponent();
cmbDataList.DataSource = GetData();
cmbDataList.DisplayMember = "Name";
cmbDataList.ValueMember = "Price";
Now, your selected display will be synced with the value and you will be able to use it..
Get more info in here:
Populate combobox
You Need to set ValueMember You can set in this way
cmbDataList.ValueMember = "ID";
then you write the code on cmbDataList_SelectedIndexChanged Event
May be this will help you
var sel = cmbDataList.SelectedValue

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