简体   繁体   English

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

[英]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.我使用此代码从表 sql 数据库中填充我的下拉列表。 I need to show id, FirstName and LastName of each row in dropdownlist.我需要在下拉列表中显示每行的 id、FirstName 和 LastName。

for example:例如:

1-Sara Sindra
2-Michel Lafra.

but with my code just ID Displayed in dropdownlist.但我的代码只是 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);
}

You can use string.Format to merge ID and Full Name in order and then append the resulting string to ComboBox.您可以使用 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);
}

Further close connection after for loop instead of within for loop.在 for 循环之后而不是在 for 循环内进一步关闭连接。 See above snippet见上面的片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM