简体   繁体   中英

Selected Item in combobox to datagrid C# SQL

We have a combo box with different music genres. We want the selected genre, in the combo box, to show the songs in the database, of that genre, and then display it in the datagrid.

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

The code shows how we are extracting the genres from our database.

public ChooseSong()
    {
        InitializeComponent();

        _DBF = new DatabaseFacade();

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

      ...
    }

Hope you can help :)

You can get the name of the gerne from the combo box and put that gerne in the SQL Query.

Create the query like:

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

And set the datagridview.DataSource to the DataSet ds.

yourDataGridView.DataSource = ds.tables[0];

EDIT:

You can do something like:

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

Then you can do:

       public DataSet sortGenreCBox(string selectedGenre){
 SqlCommand genreBox = new SqlCommand("SELECT DISTINCT " + selectedGenre  + " FROM Sang", conn);
}
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;
    }

When we write it in, it says that it doesn't exist in the current content?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM