[英]Adding items to combobox itemsource
I am binding a data table to combobox like as i show in code below . 我将数据表绑定到组合框,如下面的代码所示。
objComboBox.ItemsSource = objDataTableNew.DefaultView;
objComboBox.DisplayMemberPath = objDataTableNew.Columns[0].ToString();
objComboBox.SelectedValuePath = objDataTableNew.Columns[1].ToString();
objComboBox.SelectedIndex = 0;
Now i want to add combo box item with display text as "select" and value as "-1" to the top of the list . 现在,我想在列表顶部添加显示文本为“ select”且值为“ -1”的组合框项目。 Directly i cant add since itemsource is bound with data table. 由于itemsource与数据表绑定,因此我无法直接添加。 I tried inserting a row to objDataTableNew at index zero . 我尝试在objDataTableNew的索引零处插入一行。 but i am having a prob . 但是我有一个问题。 0th column of datatable obtained from DB is a integer column. 从DB获得的数据表的第0列是整数列。 So i cant insert a string value "select" to that column . 因此,我无法在该列中插入字符串值“ select”。
How do i achieve this ? 我该如何实现?
This worked for me: 这对我有用:
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
将objComboBox.ItemsSource与ObservableCollection绑定,其中集合的内容为“选择”字符串+数据表项。
Try CompositeCollection in WPF. 在WPF中尝试CompositeCollection 。
<ListBox xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib">
<ListBox.Resources>
<Collections:ArrayList x:Key="TestCollection">
<System:String>1</System:String>
<System:String>2</System:String>
<System:String>3</System:String>
<System:String>4</System:String>
</Collections:ArrayList>
</ListBox.Resources>
<ListBox.ItemsSource>
<CompositeCollection>
<System:String>--Select--</System:String>
<CollectionContainer
Collection="{StaticResource TestCollection}"/>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
So in place of StaticResource
you can supply Binding
from your View Model as well. 因此,也可以代替StaticResource
从视图模型中提供Binding
。
Hope this helps. 希望这可以帮助。
The error message is pretty self explanatory. 错误消息很容易解释。 It appears you are tying to insert a string ("select") in an integer column [0]. 您似乎想在整数列[0]中插入字符串(“选择”)。 Insert the integer "-1" in [0] (integer column) and the string "select" in [1] (the string column). 在[0](整数列)中插入整数“ -1”,在[1](字符串列)中插入字符串“ select”。 Assuming [1] is a string column. 假设[1]是一个字符串列。
首先将数据绑定到数据表并创建新行到数据表
DataRow row = dt.NewRow(); row["Category"] = "<-Please select Category->"; dt.Rows.InsertAt(row, 0); CBParent.DataSource = dt;
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(objDataTable.Rows.Cast<DataRow>().Select(row => new KeyValuePair<string, string>(row[DisplayMemberColumn].ToString(), row[SelectedValueColumn].ToString())));
list.Insert(0, new KeyValuePair<string, string>("<--Select-->", "-1"));
objComboBox.ItemsSource = list;
objComboBox.DisplayMemberPath = "Key";
objComboBox.SelectedValuePath = "Value";
objComboBox.SelectedIndex = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.