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

发布于 2024-12-11 21:09:27 字数 122 浏览 0 评论 0原文

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

此致

I want to know how can I assign a SQL Server database to ItemSource property of a ComboBox (in a WPF app). I assigned the data source to the project but do not know how to assign to the property.

Best regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

剪不断理还乱 2024-12-18 21:09:27

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

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();
  }

}

you can try like this ..you can bind the item source property of combobox like this below..

ItemsSource="{Binding}"

EDIT:

Connection string :

You can add in control event or class but it should be in wpf application window.

If you create new application in visual studio or visual c# or whatever it creates window1.xaml. you need to add connection string basically in class or event in that window1.xaml not in app.config or app.xaml.

connection string define in class:

Here is example by creating a class (its sql connector instead of OleDb which i showed in 1st one):

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;
    }
}

and you can use this class in your methods:

  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>

on load function u can assign values to combobox

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();
  }

}
病女 2024-12-18 21:09:27

如果其他人来到这里(就像我一样),这里是 pratap k 代码的改进版本。只需向此方法传递 6 个参数,它就会填充您的组合框。

  1. connectionString - 连接到数据库的连接字符串的名称。如果您想在另一个班级中进行设置,只需致电
    参考,你可以相应修改代码。
  2. combobox - 要填充的组合框的名称

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

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

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

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

此外,您可以将它们传递给中的值(DisplayMemberPath 和 SelectedValuePath)。 的 XAML 代码。

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();                
        }            
    }

您 普拉塔普 k.:)

If someone else lands up here(like I did), here is the improved version of pratap k's code. Just pass 6 parameters to this method and it will fill your comboBox.

  1. connectionString - name of the connection string to connect to the DB. If you prefer to set it up in another class and just call
    the reference, you can modify the code accordingly.
  2. combobox - Name of the comboBox you want to fill

  3. query - You query to fetch the data from the database

  4. defaultValue - The default value you want to set to the comboBox

  5. itemText - This the data you want to show in the list box. This is the name of the column of the DB and is in your SELECT query.

  6. itemValue - This is the value you want to associate to the items of the combobox. This is also a column in your SELECT query and is the name of a column in your db. (If you don't need it, remove it from the code and the parameter too.

Also, you can pass these to values (DisplayMemberPath and SelectedValuePath) in your XAML code.

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();                
        }            
    }

Thanks pratap k. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文