How to test which combobox has been most recently changed? WPF - c#

Is there a way to check to see which combobox which value has been most recently changed?
how to check if item is selected from a comboBox in C#
I know you can do this,
if (MyComboBox.SelectedIndex >= 0)
{
//do stuff
}
The problem I am having is that I am combining Event Handlers in to one handler due to the amount of comboboxes and having one event for each combobox really is not practical if I can help it.
Is there a way to have a variable assigned giving you the name of the combobox which value has been most recently changed? Or will I have to use individual event handlers for each combobox?

Actually It will be very easy to track most recent combobox change when you using single event handler for all combobox. You can do by following way.
string lastComboName=""; // define global variable
//common event handler for all combobox
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cmb = (ComboBox)sender;
lastComboName = cmb.Name;
}

Hope that each comboBox having an unique name, then we can use those name to identify which one is the sender of event: Now consider the following code for this:
private void CboFirst_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox selctedComboBox = sender as ComboBox;
string ComboName = selctedComboBox.Name;
// Do something
}
Now tracking the last updated ComboBox, You can achieve this by keeping a blobal variable and update it in every trigger so Every time it holds the Latest value( the name of the combobox)

Related

Windows 10 uwp listview selection changed not working

Windows 10 uwp app with a listview to just list out strings. First of all, I have an observable collection of strings in my xaml code behind. Because I still dont understand proper data binding in xaml, I am currently adding the strings to tje listview by doing a foreach loop on the observable collection and then doing
Listview1.Items.Add (new TextBlock {Text = myString});
However, is binding in this case as easy as setting my listview ItemsSource to my observablecollection?
My main issue though is I want to know when a user selects a string in the listview and what string they selected. So, I wired up to the listview SelectionChanged event. This event will raise when I select an item in the list, however
var selectedString = e.AddedItems.First().ToString();
Does not give me the selected string value. Also, there seems to be a possible recursion issue with this event. At one point, my breakpoint hit twice even though I had only selected an item in the listview one time.
So, main question is how to i get the selected string from the listview but also would appreciate suggestions or comments on data binding and if there could be recursion with this event.
EDIT: After trying the last two answers, I am still having some issues here. I cannot get the string that is selected. Using both answers below, I get the same results. First, there is some recursion because clearly the event does fire twice most times even when the list is selected only one time. Also, in both cases, the string is never populated with the selection. In fact, the breakpoint will hit at the line but then skip to the end of the event handler method and I cannot inspect any of the variables or arguments. I even wrapped it up in a try catch block but it never runs the rest of the code in the try block and never catches an exception. All it does is skip to the end of the event handler method but then take me to a file called SharedStubs.g.cs and in there, it hits at the end of this method
// Signature, Windows.UI.Xaml.UnhandledExceptionEventHandler.Invoke, [rev] [return] [Mcg.CodeGen.ComHRESULTReturnMarshaller] void__int, [rev] [in] [Mcg.CodeGen.WinRTInspectableMarshaller] object____mcg_IInspectable, [rev] [in] [GenericTypeMarshaller] -> T,
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
internal static int Proc_object__TArg0__<TArg0>(
object __this,
global::System.Runtime.InteropServices.__vtable_IInspectable* unsafe_sender,
void* unsafe_e,
global::System.IntPtr __methodPtr)
{
// Setup
object sender = default(object);
TArg0 TArg0__arg = default(TArg0);
try
{
// Marshalling
sender = global::System.Runtime.InteropServices.McgMarshal.IInspectableToObject(((global::System.IntPtr)unsafe_sender));
TArg0__arg = (TArg0)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_e),
typeof(TArg0).TypeHandle
);
// Call to managed method
global::McgInterop.Intrinsics.HasThisCall__Proc_object__TArg0__<TArg0>(
__this,
__methodPtr,
sender,
TArg0__arg
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return global::McgInterop.Helpers.S_OK;
}
catch (global::System.Exception hrExcep)
{
// ExceptionReturn
return global::System.Runtime.InteropServices.McgMarshal.GetHRForExceptionWinRT(hrExcep);
}
}
And the sender in this method is ListView. After it hits in this method, the debugger just sort of hangs. I never get a real exception or error and it never really stops. I can hit continue but it just sits idle. So, the above is the only clue I really have. Not sure why this would hit but not the try/catch block and why I would never get any further exception, stack trace, etc...
Thanks!
Can you please try this one?
private void Listview1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TextBlock textBlock = (sender as ListView).SelectedItem as TextBlock;
string value = textBlock.Text;
// OR
string value2 = (e.AddedItems[0] as TextBlock).Text;
// OR
string value3 = (e.AddedItems.First() as TextBlock).Text;
}
First of all, binding string items to a listview requires one line of code. You don't have to create a XAML template for that since you're not binding a object with properties. You can just do this:
Listview1.ItemsSource = YourObservableCollection();
It will bind your collection to your ListView.
As for the selection event, instead of SelectionChanged, you can use ItemClick event. The event args will give you the selected item aka the string by calling e.ClickedItem.
First, enable your ListView1's IsItemClickEnabled. Set it from false to true. Then add the ItemClick event.
private void ListView1_ItemClick(object sender, ItemClickEventArgs e)
{
e.ClickedItem;
}
This will return the value selected, in your case, the string.
Hope it helps!
You get the currently selected item in a ListView using the SelectedItem property and since you are adding TextBlock elements to the Items collection you should cast the SelectedItem property to a TextBlock and then access its Text property to get the string value:
private void Listview1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TextBlock textBlock = Listview1.SelectedItem as TextBlock;
if (textBlock != null)
{
string s = textBlock.Text;
}
}
you can also use SelectionChanged event to get the value selected by user.
Here is how the code will look like :
In XAML :
ListView Name="sourceList"
ItemsSource="{Binding itemsource}"
SelectionChanged="sourceList_SelectionChanged"
In Code behind :
private void sourceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedSource = Convert.ToString(((ListView)sender).SelectedItem);
}

Get selected Item name from combo box

I have a combo box as shown in the code below. I would like to display the name of the selection in a message box when I select it. What I am trying is -
<dxb:BarEditItem.EditTemplate>
<DataTemplate>
<dxe:ComboBoxEdit x:Name="PART_Editor"
SelectedIndexChanged="OnSelectedIndexChanged" Name="comboBox">
<dxe:ComboBoxEdit.Items>
<system:String>Item1</system:String>
<system:String>Item2</system:String>
</dxe:ComboBoxEdit.Items>
</dxe:ComboBoxEdit>
</DataTemplate>
How can I add the code in the backend for getting the selected name inside a message box?
Do you mean to handle this on the SelectedIndexChanged event? If so you can get the combobox that triggered the event.
private void OnSelectedIndexChanged(object sender, RoutedEventArgs e)
{
ComboBox cb = (ComboBox)sender;
string selectedText = cb.SelectedText;
//Code to display the selectedText into a message box
}
I'm not sure what do you mean by the "name of the selection", so I'm assuming you want to get hold of the text that is displayed in the combo, which represents the selected item.
Once you have the combo itself in your hands:
private void OnSelectedIndexChanged(object sender, RoutedEventArgs e)
{
var combo = (ComboBoxEdit)sender;
(...)
}
you have several options. Most reliable one (in my opinion) would be to use combo.DisplayText property, which is a read-only property holding the actual text that should be displayed in the combo (with consideration of DisplayMember property, DisplayTextConverter property and CustomDisplayText event).
Another option (in your particular case) would be (string)combo.SelectedItem. Note though, that combo.SelectedItem returns the actual selected item and not it's text representation. The above is fine as long as items are of type string. Should they not be, you'll get an InvalidCastException. Also, it's possible that in that case what you get might not be what you see (as noted in previous paragraph there are several ways to modify the displayed text).
Yet another option is combo.Text, which takes into consideration DisplayMember, but not DisplayTextConverter nor CustomDisplayText.
EDIT
Turns out that at the time SelectedIndexChanged is raised, DisplayText property is not yet updated to reflect the newly selected item (which isn't especially surprising). To deal with that, you should "postpone" the retrieval of the DisplayText value. I'd personally go with something along these lines (using a Dispatcher associated with the combo):
private void OnSelectedIndexChanged(object sender, RoutedEventArgs e)
{
var combo = (ComboBoxEdit)sender;
combo.Dispatcher.BeginInvoke(new Action(() =>
{
var text = combo.DisplayText;
(...)
}));
}
just type comboboxName.Text and you will get the selected item of combobox

Remove something added by a particular event - c#

I have a piece of code that will add the selected item of a combobox to a listbox when a checkbox is checked. I would like to remove that selected item to be removed from the listbox when the checkbox is unchecked.
My problem is I cant simply repeat the code for removal to be the same as add because the combobox selection will different or empty when unchecked.
This is how it currently looks:
private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
listBox2.Items.Add(comboBox1.SelectedItem);
}
if (checkBox1.Checked == false)
{
listBox2.Items.Remove(comboBox1.SelectedItem);
}
So I need a way of removing whatever was added by that check change instead of removing the selected index of the combobox. Please consider that there may be multiple lines in the listbox added by multiple different checkboxes.
You simply need to store the added item and remove it.
private object addedItem;
private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
addedItem = comboBox1.SelectedItem;
listBox2.Items.Add(addedItem);
}
else
{
listBox2.Items.Remove(addedItem);
}
}
You may also need to check SelectedItem is null before adding/removing the item.
Focusing on the part where you said there might be multiple different checkboxes,
you need to store one item per checkbox.
You can write your own child class of the checbox control to add this feature, or simply use the Tag property.
You can also indicate which checkbox is linked to which combobox in the same way. Either child class or use the Tag property.
In my example, I'll assume you've referenced the combobox from the checkbox using the Tag property.
You can do it manually like this
checkBox1.Tag = comboBox1;
or hopefully you can automate it if you are generating these on the fly.
Here is the general idea of how the checkbox event should look.
The event is is utilising the sender argument, which means you should hook up all your checkboxes CheckedChanged events to this one handler. No need to create separate handlers for each.
private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
var checkBox = (CheckBox)sender;
var comboBox = (ComboBox)checkBox.Tag;
if (checkBox.Checked && comboBox.SelectedItem != null)
{
listBox2.Items.Add(comboBox.SelectedItem);
comboBox.Tag = comboBox.SelectedItem;
}
if (!checkBox.Checked && comboBox.Tag != null)
{
listBox2.Items.Remove(comboBox.Tag);
}
}

Events to make a DataGridView ComboxColumn affect the collection of another ComboBox Column

You'd think I'd be able to find a code example for this: Let's say I have a WinForm with a DataGridView and 2 ComboBoxColumns. The columns are not databound, they have a static collection for all their options. So I want to programatically change the item collection for Column 2 as changes are made (ie different selections) to Column 1. Any examples for this please?
Your problem is how to register SelectedIndexChanged event handler for your ComboBox under the DataGridViewComboBoxColumn, we all know that DataGridViewComboBoxColumn doesn't have such an event. To solve this, we have several ways for DataGridViewComboBoxColumn with data bound source or static source. Because you said your Items are added normally for your combobox so I have this solution:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if(e.Control is DataGridViewComboBoxEditingControl){
((DataGridViewComboBoxEditingControl)e.Control).SelectedIndexChanged -= SelectedIndexChanged;
((DataGridViewComboBoxEditingControl)e.Control).SelectedIndexChanged += SelectedIndexChanged;
}
}
private void SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl combo = sender as DataGridViewComboBoxEditingControl;
//Change the source of the other combobox column accordingly
//
//////////////////////////////////////////////////////////
}
You have to add your code to re-populate the source of the other combobox column accordingly, that's up to you.

C# ComboBox in DropDownList style, how do I set the text?

I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form_load doesn't work either. Can anyone help?
The code you specify:
comboBox.Text = "Wildcards";
...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list.
If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded.
For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this:
private void button1_Click(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains("Wildcards"))
{
comboBox1.Items.Add("Wildcards");
}
comboBox1.Text = "Wildcards";
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains("Wildcards"))
comboBox1.Items.Remove("Wildcards");
}
That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.
You can select one of items on formload or in form constructor:
public MyForm()
{
InitializeComponent();
comboBox.SelectedIndex = 0;
}
or
private void MyForm_Load(object sender, EventArgs e)
{
comboBox.SelectedIndex = 0;
}
Try this
comboBox1.SelectedValue = "Wildcards";
This may be a possible solution:
comboBox1.SelectedValue = comboBox1.Items.FindByText("Wildcards").Value;

Categories