简体   繁体   中英

How to fill dropdownlist from a table with ID+First name+last name of a row

I use this code for fill my dropdownlist from a table sql database. I need to show id, FirstName and LastName of each row in dropdownlist.

for example:

1-Sara Sindra
2-Michel Lafra.

but with my code just ID Displayed in dropdownlist.

public void Load_Combo(string Query, ComboBox cb)
{
    string ConnectionString = @"Data Source=.\sqlexpress;AttachDbFilename=|DataDirectory|\mydatabase.mdf;user id = sa;password = 1111111111";

    SqlConnection connection = new SqlConnection();

    cb.Items.Clear();

    connection.ConnectionString = ConnectionString;
    connection.Open();

    SqlDataAdapter adaptor = new SqlDataAdapter(Query, connection);
    DataTable dtt = new DataTable();
    adaptor.Fill(dtt);

    for (int i = 0; i < dtt.Rows.Count; i++)
        cb.Items.Add(dtt.Rows[i][0].ToString());
        connection.Close();

}


private void btn1_Click(object sender, EventArgs e)
{
   Load_Combo("SELECT ID , FName + ' ' + LName AS Fullname FROM studentstbl", cmb_cash1);
}

You can use string.Format to merge ID and Full Name in order and then append the resulting string to ComboBox.

public void Load_Combo(string Query, ComboBox cb)
{
    string ConnectionString = @"Data Source=.\sqlexpress;AttachDbFilename=|DataDirectory|\mydatabase.mdf;user id = sa;password = 1111111111";

    SqlConnection connection = new SqlConnection();

    cb.Items.Clear();

    connection.ConnectionString = ConnectionString;
    connection.Open();

    SqlDataAdapter adaptor = new SqlDataAdapter(Query, connection);
    DataTable dtt = new DataTable();
    adaptor.Fill(dtt);

    for (int i = 0; i < dtt.Rows.Count; i++)
        cb.Items.Add(string.Format("{0}-{1}", dtt.Rows[i][0], dtt.Rows[i][1]));
    }       

    connection.Close();
}


private void btn1_Click(object sender, EventArgs e)
{
   Load_Combo("SELECT ID , FName + ' ' + LName AS Fullname FROM studentstbl", cmb_cash1);
}

Further close connection after for loop instead of within for loop. See above snippet

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