将SQL数据库附加到ComboBox.ItemSource(WPF)

我想知道如何将一个SQL Server数据库分配给combobox的ItemSource属性 (在WPF应用程序中)。 我将数据源分配给项目,但不知道如何分配给该属性。

最好的祝福

你可以尝试这样的..你可以像下面这样绑定组合框的项目源属性..

的ItemsSource = “{结合}”

编辑:

连接字符串:

你可以添加控制事件或类,但它应该在WPF应用程序窗口。

如果您在Visual Studio或Visual C#中创建新应用程序,或者创建window1.xaml。 你需要添加连接字符串基本上在类或事件在window1.xaml不在app.config或app.xaml。

连接字符串在类中定义:

这里是通过创建一个类(它的SQL连接器,而不是我在第一个显示的OleDb)的例子:

public class ConnectionHelper { public static SqlConnection GetConnection() { string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True"; SqlConnection conn = new SqlConnection(connectionStr); return conn; } } 

你可以在你的方法中使用这个类:

  SqlConnection conn = ConnectionHelper.GetConnection(); 
  <Window ....... Loaded="OnLoad" > <Grid> <ComboBox Height="18" SelectionChanged="cmbCategory_SelectionChanged" ItemsSource="{Binding}" HorizontalAlignment="Right" Margin="0,92,17,0" Name="cmbCategory" VerticalAlignment="Top" Width="176" BorderBrush="#FFFFFFFF" SelectedIndex="0"/> </Grid> </Window> 

加载函数可以赋值给组合框

 private void OnLoad(object sender, System.EventArgs e) { ListCategories(); } private void ListCategories() { sqlCon = new SqlConnection(); sqlCon.ConnectionString = Common.GetConnectionString(); cmd = new SqlCommand(); cmd.Connection = sqlCon; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Categories"; sqlDa = new SqlDataAdapter(); sqlDa.SelectCommand = cmd; ds = new DataSet(); try { sqlDa.Fill(ds, "Category"); DataRow nRow = ds.Tables["Category"].NewRow(); nRow["CategoryName"] = "List All"; nRow["CategoryID"] = "0"; ds.Tables["Category"].Rows.InsertAt(nRow, 0); //Binding the data to the combobox. cmbCategory.DataContext = ds.Tables["Category"].DefaultView; //To display category name (DisplayMember in Visual Studio 2005) cmbCategory.DisplayMemberPath = ds.Tables["Category"].Columns["CategoryName"].ToString(); //To store the ID as hidden (ValueMember in Visual Studio 2005) cmbCategory.SelectedValuePath = ds.Tables["Category"].Columns["CategoryID"].ToString(); } catch (Exception ex) { MessageBox.Show("An error occurred while loading categories."); } finally { sqlDa.Dispose(); cmd.Dispose(); sqlCon.Dispose(); } } 

如果有其他人登陆(像我这样做),这里是pratap k代码的改进版本。 只需传递6个参数到这个方法,它会填充你的组合框。

  1. connectionString – 连接到数据库的连接字符串的名称。 如果您希望在其他课程中设置它,只需调用参考,则可以相应地修改代码。
  2. combobox – 您要填写的组合框的名称

  3. 查询 – 您查询从数据库中获取数据

  4. defaultValue – 您要设置为组合框的默认值

  5. itemText – 这是您要在列表框中显示的数据。 这是数据库列的名称,并在您的SELECT查询中。

  6. itemValue – 这是您想要关联到组合框的项目的值。 这也是您的SELECT查询中的一列,是您的数据库中的一列的名称。 (如果你不需要它,也可以从代码和参数中删除它。

另外,您可以将这些值传递给XAML代码中的值(DisplayMemberPath和SelectedValuePath)。

 public bool fillComboBox(string connectionString, System.Windows.Controls.ComboBox combobox, string query, string defaultValue, string itemText, string itemValue) { SqlCommand sqlcmd = new SqlCommand(); SqlDataAdapter sqladp = new SqlDataAdapter(); DataSet ds = new DataSet(); try { using (SqlConnection _sqlconTeam = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString)) { sqlcmd.Connection = _sqlconTeam; sqlcmd.CommandType = CommandType.Text; sqlcmd.CommandText = query; _sqlconTeam.Open(); sqladp.SelectCommand = sqlcmd; sqladp.Fill(ds, "defaultTable"); DataRow nRow = ds.Tables["defaultTable"].NewRow(); nRow[itemText] = defaultValue; nRow[itemValue] = "-1"; ds.Tables["defaultTable"].Rows.InsertAt(nRow, 0); combobox.DataContext = ds.Tables["defaultTable"].DefaultView; combobox.DisplayMemberPath = ds.Tables["defaultTable"].Columns[0].ToString(); combobox.SelectedValuePath = ds.Tables["defaultTable"].Columns[1].ToString(); } return true; } catch (Exception expmsg) { return false; } finally { sqladp.Dispose(); sqlcmd.Dispose(); } } 

感谢pratap k。 🙂