c#wpf将combobox绑定到SQL Server数据库

时间:2016-06-16 22:44:58

标签: c# sql-server wpf combobox dataset

我正在尝试将我的数据库绑定到一个组合框(“ProjectComboBox”),似乎无法让它工作。我试过在XAML中传递它,以及后端代码,但Combobox总是空白的。任何帮助将不胜感激。

SQL Server(本地)数据库:“Database1”

数据源:(DataSet1);表:(ProjectTable);

组合框名称:“ProjectComboBox”

这是我的XAML代码:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="850">
<Grid>
    <ComboBox x:Name="ProjectComboBox"
              ItemsSource="{Binding Path=ProjectTable}"
              DisplayMemberPath="ProjectName" 
              SelectedValuePath="RFIDirectory" 
              HorizontalAlignment="Left" 
              VerticalAlignment="Top" 
              Width="297" Height="26" 
              SelectionChanged="comboBox_SelectionChanged">
    </ComboBox>

这是我的后端代码:

namespace WpfApplication1

public partial class MainWindow : Window
{
    public DataSet1 ProjectTable { get; set; }
    public MainWindow()
    {
        InitializeComponent();

    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ProjectComboBox.Items.Clear();

        SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Database1;Integrated Security=True");

        try
        {
            con.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        try
        {
            SqlDataAdapter ProjectTableTableAdapter = new SqlDataAdapter("SELECT * FROM PROJECTNAME", con);
            DataSet1 ds = new DataSet1();
            ProjectTableTableAdapter.Fill(ds, "t");

            ProjectComboBox.ItemsSource = ds.Tables["t"].DefaultView;
            ProjectComboBox.DisplayMemberPath = "ProjectName";
            ProjectComboBox.SelectedValuePath = "RFIDirectory";

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

    }
}

}

1 个答案:

答案 0 :(得分:0)

  1. 您无法直接绑定到SQL Server表记录。但是,您可以绑定到表示表记录的对象列表。
  2. 正如@Paul Abbott所提到的,一旦表单加载,您必须首先初始化组合框项目。或者一个丑陋的方法是添加一个虚拟记录,一旦你选择它,将引发选择更改事件,然后你的代码将执行。
  3. 不要为连接open和sql数据适配器单独执行try-catch块。这是多余的。

  4. 在sql连接上使用using语句以正确关闭并在之后进行处置。

    public MainWindow()
    {
        InitializeComponent();
        UpdateItems(); // Maybe initialize here?
    }
    
    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ProjectComboBox.Items.Clear(); // Remove this. AFAIK, the selected item will be cleared.
        UpdateItems();
    }
    
    private void UpdateItems()
    {
        try
        {
            using(SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Database1;Integrated Security=True"))
            {
                con.Open();
                SqlDataAdapter ProjectTableTableAdapter = new SqlDataAdapter("SELECT * FROM PROJECTNAME", con);
                DataSet1 ds = new DataSet1();
                ProjectTableTableAdapter.Fill(ds, "t");
    
                ProjectComboBox.ItemsSource = ds.Tables["t"].DefaultView;
                ProjectComboBox.DisplayMemberPath = "ProjectName";
                ProjectComboBox.SelectedValuePath = "RFIDirectory";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        } 
    }
    
    <ComboBox x:Name="ProjectComboBox"
          ItemsSource="{Binding Path=ProjectTable}" // Not sure of what the impact will be by adding this because you have already defined the item source on your code-behind. I'd prefer you remove this and use XAML binding when you're following a design pattern like MVVM or MVPVM.
          DisplayMemberPath="ProjectName" 
          SelectedValuePath="RFIDirectory" 
          HorizontalAlignment="Left" 
          VerticalAlignment="Top" 
          Width="297" Height="26" 
          SelectionChanged="comboBox_SelectionChanged">
    </ComboBox>