问题
I am trying to put the content of the one column table into the listbox
. I use this code to do that.
listBox1.DataContext = ds.Tables[0];
I also tried to use this code
listBox1.ItemsSource = ds.Tables[0];
and both didn't work.
Any idea how can I do that?
namespace itinventory
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection con ;
SqlDataAdapter da ;
DataSet ds;
public MainWindow()
{
InitializeComponent();
con = new SqlConnection("Server=myserver\\sqlexpress;" + "Database=ITINVENTORY;User ID=sa;" + "Password=mypassword");
con.Open();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select DISTINCT orgcode from Employees", con);
DataSet ds = new DataSet();
da.Fill(ds,"orgcode");
listBox1.DataContext = ds.Tables[0];
}
}
}
回答1:
here is optimized codes and some suggessions for you.
string constring = @"Data Source=.\SQLEXPRESS;AttachDbFilename='D:\TEMPX\Projects X\ODataClient\ODataClient\Data\northwnd.mdf';Integrated Security=True;User Instance=True";
void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Employees", con);
da.Fill(dt);
con.Close();
}
listBox1.ItemsSource = dt.AsDataView();
}
i will not tell you about the how to write the queries. but for your question here are some points.
If you are using binding then dataContext is ok. The DataContext means you are passing a object which can be further bindable to its child properties. and you neec to bind the ItemsSource Property of ListBox. as
ItemsSource={Binding}.
<ListBox x:Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But if you are just passing the Data to List what you need to do is asssing data into ItemsSource property and that will only show the object type Full Name insteed of showing data. Use above template to show data.
another thing is that when you assing DataTable object to a itemsssource/ DataContext the source must be Enumrable so use this as DataView. its insherited from Ilist , IEnumrable. etc.
来源:https://stackoverflow.com/questions/12363369/how-can-i-bind-a-listbox-to-a-data-table-in-wpf-applications