How to Set Value of Wpf Combobox Item from C# Code

How to set value of WPF ComboBox Item from C# Code

If the value you're looking to set is only used in the back end, and not displayed to the user, the Tag property is probably your best bet.

item.Tag = fx.FunctionValue;

Set Combobox Item from C# using Value in WPF

you have to use the selectedValue property..

try the below

cBox.SelectedValue = dtable.Rows[1][0].ToString();

you can download the working sample from here..

https://drive.google.com/uc?export=download&id=0Bxxluya0NKB2dGZOMjc0SlRJVWc

Set selected item in WPF ComboBox

You have to use SelectedValue. In WPF ComboBox, there are multiple ways to achieve the same thing. So, one syntax to select an item programmatically won't work. There are various ways of adding items to ComboBox.

  1. You can set ItemsSource both declaratively or in code.
  2. You can add ComboBoxItems etc. See Items property in property window to see various item-types available.

If you are using ItemsSource with string values, then you need syntax like : cmb1.SelectedValue = "Name1"

If you are directly adding items like <ComboBox ...> <ComboBoxItem Content="Name1"/> </ComboBox/> , then you need

foreach (ComboBoxItem item in cmb2.Items)
if (item.Content.ToString() == "Name1")
{
cmb2.SelectedValue = item;
break;
}

I have posted a full working sample demonstrating how to select an item programmatically in various scenarios. Sample code (can be used as is) :

Pay attention to last one, where you have to use SelectedValuePath.

Window1.xaml

<Window x:Class="WpfApplicationBlend.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="Window1" Height="411" Width="749">

<Grid>
<Grid Margin="30,27,491,276">
<ComboBox x:Name="cmb1" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBox.ItemsSource>
<CompositeCollection>
<sys:String>Name1</sys:String>
<sys:String>Name2</sys:String>
<sys:String>Name3</sys:String>
<sys:String>Name4</sys:String>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
<TextBox x:Name="tbInput1" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
</Grid>

<Grid Margin="405,27,111,276">
<ComboBox x:Name="cmb2" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBoxItem Content="Name1"/>
<ComboBoxItem Content="Name2"/>
<ComboBoxItem Content="Name3"/>
</ComboBox>
<TextBox x:Name="tbInput2" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button2_Click"/>
</Grid>

<Grid Margin="30,207,491,96">
<ComboBox x:Name="cmb3" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" FocusVisualStyle="{DynamicResource StyleFocusDefault}">
<ComboBox.ItemsSource>
<CompositeCollection>
<sys:String>Name1</sys:String>
<sys:Boolean>True</sys:Boolean>
<sys:Int32>123</sys:Int32>
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
<TextBox x:Name="tbInput3" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button3_Click"/>
</Grid>

<Grid Margin="405,207,116,96">
<ComboBox x:Name="cmb4" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Width="210" Height="25" SelectedValuePath="Name" DisplayMemberPath="Name">
</ComboBox>
<TextBox x:Name="tbInput4" HorizontalAlignment="Left" Height="23" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="135,1,0,0" VerticalAlignment="Top" Width="75" Click="Button4_Click"/>
</Grid>
</Grid>
</Window>

Window1.xaml.cs

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Collections;

namespace WpfApplicationBlend
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();

List<Employee> employees = new List<Employee>()
{
new Employee(){Name="Name1", Age=100},
new Employee(){Name="Name2", Age=101},
};

cmb4.ItemsSource = employees;
}

private void Button1_Click(object sender, RoutedEventArgs e)
{
cmb1.SelectedValue = tbInput1.Text;
}

private void Button2_Click(object sender, RoutedEventArgs e)
{
foreach (ComboBoxItem item in cmb2.Items)
if (item.Content.ToString() == tbInput2.Text)
{
cmb2.SelectedValue = item;
break;
}
}

private void Button3_Click(object sender, RoutedEventArgs e)
{
foreach (object item in cmb3.Items)
if (item.ToString() == tbInput3.Text)
{
cmb3.SelectedValue = item;
break;
}
}

private void Button4_Click(object sender, RoutedEventArgs e)
{
cmb4.SelectedValue = tbInput4.Text;
}
}

public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
}

Add comboBox items from code behind. [WPF]

Set the items programmatically:

Code-behind:

    private void PopulateComboBox()
{
cBox.ItemsSource = new List<string> { "Item1", "Item2", "Item3"};
}

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" />

Bind to a collection of items:

    public class DummyClass
{
public int Value { get; set; }
public string DisplayValue { get; set;}
}

public ObservableCollection<DummyClass> DummyClassCollection
{
get
{
return new ObservableCollection<DummyClass>
{
new DummyClass{DisplayValue = "Item1", Value = 1},
new DummyClass{DisplayValue = "Item2", Value = 2},
new DummyClass{DisplayValue = "Item3", Value = 3},
new DummyClass{DisplayValue = "Item4", Value = 4},
};
}
}

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" ItemsSource="{Binding DummyClassCollection}" DisplayMemberPath="DisplayValue" />

How can I assign the value of a selected item in a combobox?

Have you tried this method:

Using visual studio, on the design view or .xaml if you double click the ComboBox it will autogenerate code for SelectionChanged in the .xaml.cs file. In addition, on the .xaml, when you click the ComboBox it will tell you the name of the object on the properties tab. Mine is comboBox in this example:

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem = comboBox.Items[comboBox.SelectedIndex].ToString();
Console.WriteLine(selectedItem);
}

For simplicity sake I just have it printing to the console, which will show up when you exit the program.

And so to change the value of what is shown in the comboBox at runtime for whatever reason that might be you can use something like this:

comboBox.SelectedItem = comboBox.Items[0];

Which would set it to the first item that you added to the comboBox whenever the user makes any selection.

From what I understand, you would need the text to be assigned to an item already in the ComboBox:

string MyValue = "asd";
comboBox.Items.Add(MyValue);
comboBox.Text = MyValue;

How do I make the WPF ComboBox items visible, but non-selectable?

Set an item container style that will disable each ComboBoxItem.

<ComboBox x:Name="comboBoxName" ItemsSource="{Binding Collection}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="IsEnabled" Value="False"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>

If you use code-behind, can define and apply the item container style like this.

var itemContainerStyle = new Style(typeof(ComboBoxItem));
var isEnabledSetter = new Setter(IsEnabledProperty, false);

itemContainerStyle.Setters.Add(isEnabledSetter);
comboBoxName.ItemContainerStyle = itemContainerStyle;

Retrieve the string value of a WPF ComboBox’s selected item in the code behind

Set the SelectedValuePath property to OneDName and bind the SelectedValue value property to DataBaseOneDName in your XAML markup:

<ComboBox x:Name="oneDComboBox" Grid.Row="1" Grid.Column="2" Width="120" DisplayMemberPath="OneDName"
ItemsSource="{StaticResource OneDArray}"
SelectedValuePath="OneDName"
SelectedValue="{Binding Path=DataBaseOneDName, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"
SelectionChanged="ComboBox_SelectionChanged"
/>

Then you cast SelectedItem to a OneD and then access its OneDName property:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox sourceComboBox = (ComboBox)sender;
int selectedIndex = sourceComboBox.SelectedIndex;
OneD oneD = sourceComboBox.SelectedItem as OneD;
if (oneD != null)
{
string name = oneD.OneDName;
}
string displayMemberPath = sourceComboBox.DisplayMemberPath.ToString();
}

The same thing for TwoD.

The other option would be to override the ToString() method of your classes, e.g.:

public partial class OneD
{
public string OneDName { get; set; }

public override string ToString()
{
return OneDName;
}
}

C# - WPF ComboBox not setting default value in Code-behind

Since you set the ItemsSource of your ComboBox to a List<string>, you should set the SelectedItem property to a string that is included in this list and remove SelectedValuePath="Content" from your XAML as a string has no Content property:

cmbStates.ItemsSource = new List<string>() {"OH", "VA", "CA", "TN", "CA", "DE"};
cmbStates.SelectedItem = "CA";

XAML:

<ComboBox x:Name="cmbStates" IsEditable="True" SelectionChanged="cmbStates_SelectionChanged" />


Related Topics



Leave a reply



Submit