mercredi 15 juin 2016

C#, Extract data from SQL based on search criteria given in a form

I have following combo boxes bound with data from a sql table.

  • cmbClassification
  • cmbAuthor
  • cmbPublisher
  • cmbType

I need to extract data based on selected values in these combo boxes.

For example: If I left cmbClassification blank and select values for other 3 combo boxes, my datagridview should show all the data for specific author, specific publisher & specific type regardless of the classification.

I know how to do this for two searching items (using if). but i have 4 items and no idea.

Code for two instances

I think there are 10 search patterns for these 4 combo boxes. how can i handle this? If there are only 2 combo boxes there will be 3 patterns which i will handle as follows:

string con = @"Data Source=ABU_DHABI-1SQLEXPRESS;Initial Catalog=SLIS;Integrated Security=True";


private void btnView_Click(object sender, EventArgs e)
{
    if (cmbAuth.Text == "" && cmbClassi.Text =="")
    {
        SqlConnection Icon = new SqlConnection(con);
        String Query = "SELECT * FROM Books";
        SqlCommand Command = new SqlCommand(Query, Icon);
        SqlDataAdapter da = new SqlDataAdapter(Command);
        DataTable dt = new DataTable();
        da.Fill(dt);
        BrDataGrid.DataSource = dt;
    }

    if (cmbAuth.Text == "" && cmbClassi.Text != "")
    {

        SqlConnection Icon = new SqlConnection(con);
        String Query = "SELECT * FROM Books WHERE Classification ='" + cmbClassi.Text + "'"; ;
        SqlCommand Command = new SqlCommand(Query, Icon);
        SqlDataAdapter da = new SqlDataAdapter(Command);
        DataTable dt = new DataTable();
        da.Fill(dt);
        BrDataGrid.DataSource = dt;

    }

    if (cmbAuth.Text != "" && cmbClassi.Text == "")
    {

        SqlConnection Icon = new SqlConnection(con);
        String Query = "SELECT * FROM Books WHERE Author ='" + cmbAuth.Text + "'"; ;
        SqlCommand Command = new SqlCommand(Query, Icon);
        SqlDataAdapter da = new SqlDataAdapter(Command);
        DataTable dt = new DataTable();
        da.Fill(dt);
        BrDataGrid.DataSource = dt;

    }
}

Aucun commentaire:

Enregistrer un commentaire