[英]WPF and SQL Server 2008 R2 DB
Now when i press the Button the data doesn't show up in the List box , any help ? 现在当我按下按钮时,数据没有出现在列表框中,有什么帮助吗? i want to get the data from database and show it in a list box , so the user can select items from it.
我想从数据库中获取数据并将其显示在列表框中,以便用户可以从中选择项目。 i'm using WPF and SQL server 2008 R2 ..
我正在使用WPF和SQL Server 2008 R2 ..
private void button1_Click(object sender, RoutedEventArgs e) { private void button1_Click(object sender,RoutedEventArgs e){
SqlConnection myConnection = new SqlConnection("user id=userid;" +
"password=password;server=localhost;" +
"Trusted_Connection=yes;" +
"database=db1; " +
"connection timeout=30");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
try
{
myConnection.Open();
}
catch (Exception ex)
{
textBlock1.Text = "" + (ex.ToString());
}
da.SelectCommand = new SqlCommand("Select * FROM Products", myConnection);
da.Fill(ds,"Products");
listBox1.DataContext = ds;
}
Firstly, its probably easier to bind to the itemsSource rather than the datacontext 首先,它可能更容易绑定到itemsSource而不是datacontext
Secondly, you're trying to bind your listbox directly to a dataset, which i don't think is possible. 其次,您正试图将列表框直接绑定到数据集,我认为这是不可能的。 I would create a dataview property and set that to ds.Tables[0].DefaultView.
我将创建一个dataview属性并将其设置为ds.Tables [0] .DefaultView。 Then in your listbox xaml code to show the columns put:
然后在你的listbox xaml代码中显示放置的列:
<ListView ItemsSource="{Binding Path=myDataViewProperty}">
<ListView.View>
<GridView>
<GridViewColumn Header="Column1" DisplayMemberBinding="{Binding Column1}"/>
<GridViewColumn Header="Column2" DisplayMemberBinding="{Binding Column2}"/>
</GridView>
</ListView.View>
</ListView>
thirdly, are you sure a listbox is the most suitable control for what you wish to display? 第三,你确定列表框是你想要显示的最合适的控件吗? the datagrid may be a better choice.
数据网格可能是更好的选择。
You have to define your bindings, setting the DataContext alone doesn't fill the data, it just declares the source where the bound data comes from. 您必须定义绑定,单独设置DataContext不会填充数据,它只是声明绑定数据来源的来源。
<ListBox ItemsSource="{Binding Tables[0]}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
or if you just want to display a single value in your listbox: 或者如果您只想在列表框中显示单个值:
<ListBox ItemsSource="{Binding Tables[0]}" DisplayMemberPath="ProductName"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.