【问题标题】:c# wpf bind combobox to SQL Server databasec# wpf 将组合框绑定到 SQL Server 数据库
【发布时间】:2016-10-18 15:25:05
【问题描述】:

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

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

数据源:(DataSet1);表:(项目表);

组合框名称:“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());
        }

    }
}

}

【问题讨论】:

  • 您正在填充comboBox_SelectionChanged 中的组合框,该组合框永远不会触发,因为组合框为空,因此无法更改任何内容。我希望这是在InitializeComponent(); 之后缺少的}

标签: c# sql-server wpf combobox dataset


【解决方案1】:
  1. 您不能直接绑定到 SQL Server 表记录。但是,您可以绑定到表示表记录的对象列表。
  2. 正如@Paul Abbott 所提到的,您必须在表单加载后首先初始化组合框项。或者,一种丑陋的做法是添加一个虚拟记录,一旦您选择它,将引发选择更改事件,然后您的代码将执行。
  3. 不要为您的连接打开和 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>
    

【讨论】:

    猜你喜欢
    • 2022-10-07
    • 2014-02-03
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2018-11-12
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多