【问题标题】:Selected Item in combobox to datagrid C# SQL组合框中的选定项目到数据网格 C# SQL
【发布时间】:2015-07-19 09:31:12
【问题描述】:

我们有一个包含不同音乐流派的组合框。我们希望在组合框中选择的流派在数据库中显示该流派的歌曲,然后将其显示在数据网格中。

public DataSet sortGenreCBox()
    {
        conn.Open();

        SqlCommand genreBox = new SqlCommand("Select Distinct Genre From Sang", conn);
        SqlDataAdapter adapt = new SqlDataAdapter(genreBox);
        DataSet ds = new DataSet();
        adapt.Fill(ds);

        conn.Close();

        return ds;
    }

代码显示了我们如何从数据库中提取流派。

public ChooseSong()
    {
        InitializeComponent();

        _DBF = new DatabaseFacade();

        DataSet dsGenreBox = _DBF.sortGenreCBox();
        DataTable dtGenreBox = dsGenreBox.Tables[0];
        sortByGenreCBox.DataContext = dtGenreBox;
        sortByGenreCBox.DisplayMemberPath = dtGenreBox.Columns[0].ToString();

      ...
    }

希望你能帮忙:)

【问题讨论】:

  • 问题出在哪里?
  • 我们希望组合框中选择的流派,在数据库中显示该流派的歌曲,然后将其显示在数据网格中。但我们不知道怎么做?那是我们的问题:-)
  • 你是在关注 MVVM 还是只是在后面的代码中获取数据?
  • 抱歉,我们不知道 MVVM 是什么?你能更具体吗:-) 谢谢

标签: c# sql wpf datagrid combobox


【解决方案1】:

您可以从组合框中获取 gerne 的名称并将该 gerne 放入 SQL 查询中。

创建如下查询:

 SqlCommand genreBox = new SqlCommand("SELECT DISTINCT " + sortByGenreCBox.selectedItem  + " FROM Sang", conn);

并将 datagridview.DataSource 设置为 DataSet ds。

yourDataGridView.DataSource = ds.tables[0];

编辑:

你可以这样做:

public ChooseSong()
{
   string selectedGerne = sortByGerneCBox.selectedItem.text;
   DataSet ds = DatasortGenreCBox(selectedGerne);

那么你可以这样做:

       public DataSet sortGenreCBox(string selectedGenre){
 SqlCommand genreBox = new SqlCommand("SELECT DISTINCT " + selectedGenre  + " FROM Sang", conn);
}

【讨论】:

  • 我们无法在 'string selectedGenre = sortByGenreCBox.selectedItem' 之后输入 .text
  • 对不起,你需要做 .toString()。
  • 但是这些都是基本的东西,可能你需要对你遇到的问题做更多的研究。这一切都已经在某个地方得到了回答。祝你好运。附言请标记为答案
  • “DatasortGenreCBox”是什么意思?如果您提供更多帮助,我将标记为答案:p
  • 这是您自己为您的组合框创建的名称?
【解决方案2】:
public DataSet sortGenreCBox()
    {
        conn.Open();

        SqlCommand genreBox = new SqlCommand("Select Distinct" + sortByGenreCBox.SelectedItem + "from Sang", conn);
        SqlDataAdapter adapt = new SqlDataAdapter(genreBox);
        DataSet ds = new DataSet();
        adapt.Fill(ds);

        conn.Close();

        return ds;
    }

我们写进去的时候,说当前内容中不存在?

【讨论】:

  • 你在那里写的只会返回类型,你需要使用完整的SQL语句'Select stuff From place WHERE something to limit by'
猜你喜欢
  • 2015-07-30
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多