使用列表框中显示的项目也传递值Winforms c#

时间:2014-03-02 21:44:51

标签: c# winforms listbox

我想从上面的数据库查询中填充一个列表框。列表框正确显示" PLAYER"结果作为items.I还想为所有这些项目分配一个值成员作为" ID"来自database.How它可以是这个吗?

   SqlDataAdapter sdaa = new SqlDataAdapter("SELECT PLAYERS.ID, CAST(PLAYERS.NO AS VARCHAR) + ', ' + PLAYERS.FIRSTNAME AS PLAYER FROM PLAYERS INNER JOIN TEAMS ON PLAYERS.TEAM_ID = TEAMS.ID WHERE (TEAMS.NAME =oly ", con);
        DataTable dta = new DataTable();
        sdaa.Fill(dta);

            for (int i = 0; i < dt.Rows.Count; i++)
        {

            listBox1.Items.Add(dt.Rows[i]["PLAYER"].ToString());
        }

1 个答案:

答案 0 :(得分:2)

您必须将dataTable分配给listbox.DataSource,然后设置ValueMemeber(隐藏字段)并显示成员

SqlDataAdapter sdaa = new SqlDataAdapter("SELECT PLAYERS.ID, CAST(PLAYERS.NO AS VARCHAR) + ', ' + PLAYERS.FIRSTNAME AS PLAYER FROM PLAYERS INNER JOIN TEAMS ON PLAYERS.TEAM_ID = TEAMS.ID WHERE (TEAMS.NAME =oly ", con);
    DataTable dta = new DataTable();
    sdaa.Fill(dta);
    listbox3.DataSource=dta;
    listbox3.DisplayMember="PLAYER";
    listbox3.ValueMember="ID";