Question

I am making a Windows Form in C#.I have a DataGridView, all I need to bind this grid view to database with a where clause and whose value will be equal to combobox selected item.

I have done something like this:

      private void combsalesid_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlCommand cmr = DataConnection.GetConnection().CreateCommand();
        cmr.CommandText = "select * from SalesOrder where SalesId = @salesis";
        cmr.Parameters.Add(new SqlParameter("@salesis", combsalesid.SelectedItem.ToString()));
        SqlDataAdapter da = new SqlDataAdapter(cmr);
        DataSet ds = new DataSet();
        da.Fill(ds);
        grdsalesorder.DataSource = ds;

        cmr.Dispose();
        DataConnection.CloseConnection();
    }

But it's not working.

Was it helpful?

Solution

  • What is the value of combsalesid.SelectedItem.ToString()?

    I guess combsalesid is bound to a Datatable, so Selecteditem.ToString() returns the container object (a System.Data.DataRowView).

    If yes, you just need to cast the SelectedItem into DataRowView in order to get a value from this DataRowView.

    Take a look at this post, listbox selected item give me " System.Data.DataRowView" , C# winforms. It refers to ListBox but it is the same issue.

  • Then when you assign a Dataset as DataSource for your DataGridvView, you need also to set the DataMember property which would be the name of the DataTable. Another way is to pass the DataTable as datasource.

    grdsalesorder.DataSource = ds.Tables(0);  
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top