我正在尝试从WPF ComboBox获取文本,当它将选择但无法获取任何文本时。以下是我尝试过的代码。如果有人在我选择不同的内容时请帮助我从ComboBox获取文本。请注意,ComboBox将从sql server加载完美的数据!
我的XAML代码是:
<ComboBox x:Name="comboID" TabIndex="27" SelectedValuePath="Content" SelectionChanged="comboID_SelectionChanged" HorizontalAlignment="Left" Margin="694,396,0,0" VerticalAlignment="Top" Width="165"/>
下面是我尝试的C#代码示例:
string str1 = comboID.SelectedItem.ToString();
string str2 = comboID.SelectedValue.ToString();
string str3 = comboID.Text;
ComboBoxItem cmb = comboID.SelectedItem as ComboBoxItem;
var myVal = sender as ComboBox;
string value = comboID.SelectedItem as string;
答案 0 :(得分:1)
使用此代码而非您的代码在组合框中添加项目:
SqlConnection conn = new SqlConnection("your connection");
SqlCommand cmnd = new SqlCommand();
SqlDataReader sdr = null;
conn.Open();
cmnd.Connection = conn;
String query = "Select ID from Seller ORDER BY ID";
cmnd.CommandText = query;
sdr = cmnd.ExecuteReader();
while (sdr.Read())
{
comboID.Items.Add(sdr.GetString(0));
}
现在你可以使用:
string str = comboExporterID.SelectedItem.ToString();
答案 1 :(得分:0)
我创建了一个简单的代码,为您提供一个粗略的想法。
我的Xaml
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="350">
<StackPanel Orientation="Horizontal">
<Label Content="Select Item" x:Name="LblSelectNumber" MinWidth="50px" Margin="5"></Label>
<ComboBox x:Name="ComboId" DisplayMemberPath="Number"
SelectedValuePath="Content" SelectionChanged="ComboID_OnSelectionChanged" MinWidth="100"
HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" />
</StackPanel>
</Window>
我的代码
public partial class MainWindow : Window
{
private readonly List<MyItem> _items;
public MainWindow()
{
InitializeComponent();
_items = new List<MyItem>
{
new MyItem{Content = "Test1",Number = "One"},
new MyItem{Content = "Test2",Number = "Two"},
new MyItem{Content = "Test3",Number = "Three"}
};
ComboId.ItemsSource = _items;
}
private void ComboID_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(ComboId.SelectedValue.ToString());
}
}
public class MyItem
{
public string Content { get; set; }
public string Number { get; set; }
}
请注意DisplayMemberPath
ComboBox
财产的使用情况
一个简单的建议。创建应用程序时请使用 MVVM 模式,因为它可以帮助您长期维护解决方案。使用MVVM模式
可以非常轻松地完成上面所做的工作答案 2 :(得分:0)
简单的代码。试试这个,应该工作
<强> string s = comboID.text;
强>
答案 3 :(得分:0)
将标签属性添加到组合框:
<Comboboxitem Tag="This Value"/>
然后
GetValue=ComboBoxName.SelectedItem.Tag.ToString()
GetValue将是“This Value”而不是System.windows.combobox blah blah blah ..