我正在使用 listBox 来显示搜索值的结果。我希望在搜索一个值后,用户将从搜索结果中选择一个值,其 ID 即 PK(Primaray Key) 应该传递给选定的结果而不是该选定的项目。http://i.stack.imgur.com/NaiK0.png例如,在附加图片中,我希望当用户点击“assignment7”时,它的 id 值(即8 )应该传递给选定的结果字段。我该怎么做。需要你的指导。谢谢你!
这里我的代码是:
<ListBox Grid.Row="1" SelectionMode="Single" SelectionChanged="PrintText" Background="DarkGray" Visibility="Collapsed" Height="Auto" HorizontalAlignment="Left" Margin="156,36,0,0" Name="listBox1" VerticalAlignment="Top" Width="191" UseLayoutRounding="True" />
<Grid>
<TextBlock Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,0" x:Name="textBlock1" Text="For Search Type here" VerticalAlignment="Top" Height="auto" Width="auto" Foreground="White" />
<TextBox Grid.Row="1" HorizontalAlignment="Left" Margin="156,12,0,246" x:Name="textBox1" Width="191" TextWrapping="NoWrap" TextChanged="textBox1_TextChanged" />
<ListBox Foreground="White" Grid.Row="1" SelectionMode="Single" SelectionChanged="PrintText" Background="DarkGray" Visibility="Collapsed" Height="Auto" HorizontalAlignment="Left" Margin="156,36,0,0" Name="listBox1" VerticalAlignment="Top" Width="191" UseLayoutRounding="True" />
<TextBox Grid.Row="1" Height="16" HorizontalAlignment="Left" Margin="389,0,0,248" x:Name="txtSelectedItem" VerticalAlignment="Bottom" Width="91" Grid.ColumnSpan="2" />
</Grid>
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string typedstring= textBox1.Text;
List<string> autolist= new List<string>();
foreach(string b in al)
{
if(!string.IsNullOrEmpty(textBox1.Text))
{
if(b.StartsWith(typedstring))
{
autolist.Add(b);
}
}
}
if(autolist.Count>0)
{
listBox1.ItemsSource = autolist;
listBox1.Visibility = Visibility.Visible;
}
else if (textBox1.Text.Equals (""))
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
else
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedItemsId = (int)listBox1.SelectedValue;
if (listBox1.ItemsSource != null)
{
listBox1.Visibility = Visibility.Collapsed;
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
if (listBox1.SelectedIndex != -1)
{
textBox1.Text = listBox1.SelectedItem.ToString();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
}
void PrintText(object sender, SelectionChangedEventArgs args)
{
Window1 neww = null;
neww = new Window1();
neww.Title = selectedItemsId.ToString();
neww.Show();
}
private void SetupListBox()
{
List<Assignment> lst = new List<Assignment>();
listBox1.ItemsSource = lst;
//This is what will be displayed
listBox1.DisplayMemberPath = "assignment_title";
//This is what will set the selected value to the property you want
listBox1.SelectedValuePath = "assignment_id";
}