【问题标题】:Attach a SQL database to ComboBox.ItemSource (WPF)将 SQL 数据库附加到 ComboBox.ItemSsource (WPF)
【发布时间】:2011-10-23 17:00:22
【问题描述】:

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

最好的问候

【问题讨论】:

  • 你想在组合框中显示什么?你能说出你想要执行的查询并展示你现在是如何执行它的吗?
  • 我想显示一列的行内容

标签: c# .net wpf windows


【解决方案1】:

你可以这样试试..你可以像下面这样绑定combobox的item source属性..

ItemsSource="{Binding}"

编辑:

连接字符串:

您可以添加控件事件或类,但它应该在 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();
  }

}

【讨论】:

  • 嗨,但是我该如何设置以及数据库在哪里?
  • 您可以获取连接字符串并使用该连接字符串从数据库中获取详细信息....数据库是sql server ...
  • 但是我在哪里写/设置连接字符串?
  • 你好;我可以定义连接字符串,但问题是我在加载类别时收到了定义的错误消息。 在我的例子中,“Category”已从表名(来自 db)和“CategoryName”和“CategoryID”从列名中替换。我该如何解决这个问题?
  • 错误信息如下:“加载类别时出错。” (这不是编译/调试错误)
【解决方案2】:

如果其他人来到这里(就像我一样),这里是 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。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2012-07-21
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多