How to store ComboBox selected Item in a Variable in WPF C#?

MERUN KUMAR MAITY 596 Reputation points
2023-03-10T20:41:58.13+00:00

Hi, I want to store ComboBox selected Item in a Variable so, that I can call or retrieve the variable later according to my needs. But I don't know How Can I do that? storing selected Index is very much easier I just need to take an integer variable and assign the selected index value into it, that's it. I give you an example, suppose if my ComboBox name is cmb1 and I want to store it's selected Index into an integer variable then my variable declaration would be

int i = cmb1.SelectedIndex;

But I don't know How Can I do for ComboBox selected Item, because selected Item is Object not any integer or string that's why most of the time I get compiler error I also try to declare it using Var but I don't get my expected result.

Now comes into the main purpose that why I want to store the ComboBox selected Item into a Variable? Actually, I can do that by just storing the selected index but if there any item source changes happens then all the previous selected index will remove. I have to match the pattern somehow.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,820 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,763 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,874 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
806 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Michael Taylor 54,221 Reputation points
    2023-03-10T22:03:08.0533333+00:00

    You cannot rely on selected index, nor would you want to. Every entry in a combo has a display text, value and index. The index is useful for interacting with the UI quickly but it is unreliable if the combo changes. The display text is what is shown to the user and may or may not line up with the value. The value is what that particular item represents and is what you should ideally be storing in a variable for later.

    Unfortunately how you do that depends on how you populated the combo box to begin with. In most WPF apps we assume you're using the MVVM pattern. But I suspect you aren't doing that here.

    Let's assume you have a fixed list of values, maybe colors. You added these using the designer. In that case the Text is the string value shown to the user. SelectedValue and SelectedItem are both ComboBoxItem. ComboBoxItem.Content gives you the content (which may not be a string).

    //When getting selected item the text is the value
    var text = cmdb1.SelectedText
    lblValue.Content = text;
    

    But if you instead bound the items to the control directly using some data type you defined then SelectedItem will be of that type instead.

    public class MyData
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    //At initialization of window
    cmb1.Items.Add(new MyData() { Id = 1, Name = "First" });
    cmb1.Items.Add(new MyData() { Id = 2, Name = "Second" });
    cmb1.Items.Add(new MyData() { Id = 3, Name = "Third" });
    
    //When getting selected item
    var item = cmb1.SelectedItem as MyData;
    
    if (item != null)
    {
        lblValue.Content = item.Name;
    };
    

    It is the item (of your type) that you should be storing off for later. It is unattached to the UI which means the UI can change without causing any issues.

    As for storing the result itself for later you can use a field in the same window if you need it to exist for the life of the window. If you need it to exist longer than the window then you have to promote it up to another object that is accessible after the window goes away.


  2. Alan Farias 750 Reputation points
    2023-03-10T22:10:08.59+00:00

    To store the selected item of a ComboBox in a variable in WPF C#, you can use the following code:

    XAML:

    <ComboBox x:Name="cmb1">
        <ComboBoxItem>Item 1</ComboBoxItem>
        <ComboBoxItem>Item 2</ComboBoxItem>
        <ComboBoxItem>Item 3</ComboBoxItem>
    </ComboBox>
    

    C#

    object selectedItem = cmb1.SelectedItem;
    

    In this code, we declare an object variable "selectedItem" to store the selected item of the ComboBox. We assign the ComboBox's SelectedItem property to this variable. Since the ComboBox items are objects, we can use the object data type to store the selected item.

    To use the selected item later, you can cast the variable back to the appropriate type. For example, if the items in the ComboBox are strings, you can cast the selected item back to a string:

    string selectedItemString = selectedItem as string;
    if (selectedItemString != null)
    {
        // Do something with the selected item string
    }
    

    This code first checks if the selected item can be cast to a string, and then uses the resulting string variable to perform further operations.


    I hope I was able to help! Don't forget to mark my answer as accepted if it was useful to you. Have a great day!


  3. Peter Fleischer (former MVP) 19,321 Reputation points
    2023-03-14T07:25:47.35+00:00

    Hi,
    you can save selected item in MemoryStream. Try following demo:

    <Window x:Class="WpfApp1.Window047"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp047"
            mc:Ignorable="d"
            Title="MERUN KUMAR MAITY_230313" Height="450" Width="800">
      <Window.DataContext>
        <local:ViewModel/>
      </Window.DataContext>
      <StackPanel>
        <Button Content="Add Item" Command="{Binding}" CommandParameter="Add" Margin="10"/>
        <Button Content="Save Selected Item" Command="{Binding}" CommandParameter="Save" Margin="10"/>
        <ComboBox ItemsSource="{Binding ItemsList}" SelectedItem="{Binding SelectedItem}" DisplayMemberPath="Info" Margin="10"/>
      </StackPanel>
    </Window>
    

    ViewModel:

    using System;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Text;
    using System.Windows;
    using System.Windows.Data;
    using System.Windows.Input;
    using System.Xml.Serialization;
    
    namespace WpfApp047
    {
    	public class ViewModel : ICommand
    	{
    		public ViewModel()
    		{
    			for (index = 1; index < 5; index++) col.Add(new Data() { ID = index, Info = $"Row {index}" });
    			cvs.Source = col;
    		}
    
    		private int index;
    		private Random rnd = new Random();
    
    		private ObservableCollection<Data> col = new ObservableCollection<Data>();
    		private CollectionViewSource cvs = new CollectionViewSource();
    		public object ItemsList { get => cvs.View; }
    
    		public Data SelectedItem { get; set; }
    
    		public event EventHandler? CanExecuteChanged;
    		public bool CanExecute(object? parameter) => true;
    		public void Execute(object? parameter)
    		{
    			switch (parameter?.ToString())
    			{
    				case "Add":
    					col.Insert(rnd.Next(1, col.Count), new Data() { ID = index++, Info = $"Row {index - 1}" });
    					break;
    				case "Save":
    					if (SelectedItem != null)
    					{
    						XmlSerializer ser = new XmlSerializer(typeof(Data));
    						using (MemoryStream ms = new MemoryStream())
    						{
    							ser.Serialize(ms, SelectedItem);
    							MessageBox.Show(Encoding.ASCII.GetString(ms.ToArray()));
    						}
    					}
    					break;
    				default:
    					break;
    			}
    		}
    	}
    
    	public class Data
    	{
    		public int ID { get; set; }
    		public string Info { get; set; }
    	}
    }
    

    Result:

    x

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.