简体   繁体   中英

Combo box bound to a field required to show All before a selection is made on the Combo box

I have created a Combo box bound to "Clinics" field of a table. I wanted to show "All" on the first line of the Combo box list to show all activities of the clinics by default in a table. When a specific clinic is selected it shows the activities of the selected clinic. My script looks like this:

[My Code looks like this]

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(mainconn);
        string sqlquery = "select * from [dbo].[EC_HARS_DQ]";
        SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
        sqlconn.Open();
        SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
        DataTable dt = new DataTable();
        sdr.Fill(dt);
        comboBox1.DisplayMember = "clinic";
        comboBox1.DataSource = dt;
        sqlconn.Close();


    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(mainconn);
        string sqlquery = "select * from [dbo].[EC_HARS_DQ] where clinic='"+comboBox1.Text.ToString()+"'";
        SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
        sqlconn.Open();
        SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
        DataTable dt = new DataTable();
        sdr.Fill(dt);
        dataGridView1.DataSource = dt;
        sqlconn.Close();
    }
}

}

First off, refrain from SELECT * , instead select only needed columns.

You can add All using a UNION.

In this example, table name is Categories with the intent to provide the primary key for use after a selection is made and description to display.

SELECT CategoryID, CategoryName FROM dbo.Categories;

Now using a SELECT with 0 in this case to represent an identifier and 'All` to display in the ComboBox then union for all rows in the table.

SELECT 0 AS CategoryID, 'All' AS CategoryName 
UNION ALL SELECT CategoryID, CategoryName FROM dbo.Categories;

在此处输入图像描述

In code you can read the data into a DataTable, set DisplayMember , in this case to CategoryName and ValueMember to CategoryID.

When a selection is made check SelectedItem , if 0 All is the selection, else an existing primary key would be used for your business logic.

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