如何使用行的 ID+名字+姓氏从 table 中填充下拉列表

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

我使用此代码从 table sql 数据库中填充我的下拉列表。 我需要在下拉列表中显示每一行的 ID、名字和姓氏。

例如:

1-Sara Sindra
2-Michel Lafra.

但我的代码只是 ID 显示在下拉列表中。

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

您可以使用string.Format按顺序合并IDFull Name,然后将结果字符串附加到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);
}

在for循环之后而不是在for循环内进一步关闭连接。见上面的片段