Eya*_*ron 5 c# sql wpf listbox populate
我一直在研究如何执行此操作很长时间,但是我一直未能就此问题获得直接的答案,因此希望您其中的StackOverflow用户能够在这里为我提供帮助。我有一个名为CategoryList的WPF ListBox和一个名为ProgramsList.sdf的SDF数据库(有两个名为CategoryList和ProgramsList的表)。我希望我的程序要做的是从CategoryList表中获取类别名称,并将其在名为CategoryList的ListBox控件中列出。
这是我尝试过的代码,但这只会导致程序崩溃。
SqlConnection myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
SqlDataReader myReader = null;
myConnection.Open();
CategoryList.Items.Clear();
SqlDataReader dr = new SqlCommand("SELECT Name FROM CategoryList ORDER BY Name DESC", myConnection).ExecuteReader();
while (myReader.Read())
{
CategoryList.Items.Add(dr.GetInt32(0));
}
myConnection.Close();
Run Code Online (Sandbox Code Playgroud)
谁能帮我?提前致谢!
我会尝试这样的事情:
var myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
var cmd = new SqlCommand("SELECT Name FROM CategoryList ORDER BY Name DESC", myConnection);
myConnection.Open();
CategoryList.Items.Clear();
var sda = new SqlDataAdapter(cmd);
var ds = new DataSet();
sda.Fill(ds);
CategoryList.ItemsSource = ds.Tables["CategoryList"];
myConnection.Close();
Run Code Online (Sandbox Code Playgroud)
请注意,您需要在 CategoryList 对象中设置正确的绑定,可能通过一些 XAML,如下所示:
<ListBox>
<ListBox.Resources>
<DataTemplate x:Key="DataTemplateItem">
<Grid Height="Auto" Width="Auto">
<TextBlock x:Name="Name" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ListBox.Resources>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15336 次 |
| 最近记录: |