包含从数据库c#填充的部分的ComboBox

时间:2018-03-21 19:14:32

标签: c# sql visual-studio combobox

正如标题所示,我正在尝试为其中包含的每种类型的数据创建一个具有不同标题的ComboBox。数据来自我创建的SQL数据库。

以下是我需要的一个例子。标题后跟适当的数据。在这种情况下,每行需要两个数据库列。(我在我的例子中使用生物数据)

神经肽

C39E6.6 Npr-1

T05A1.1 Npr-2

生长抑素

F56B6.5 Npr-16

C06G4.5 Npr-17

using (SqlConnection sqlConnection = new SqlConnection(@"Data Source=Laptop-R5RMQMM8;Initial Catalog=NematodeGPCR - Version 2;Integrated Security=True"))
{
    SqlCommand sqlCmd = new SqlCommand("SELECT * FROM dbo.KnownGenes Where KnownGenes.GeneID IS NOT NULL", sqlConnection);

    sqlConnection.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();

    while (sqlReader.Read())
    {
        comboBox1.Items.Add(sqlReader["Geneid"].ToString());
        comboBox1.Items.Add(sqlReader["GeneName"].ToString());
    }

    sqlReader.Close();
}

此代码使用正确的数据库列填充我的ComboBox,但它们不在一行中,并且没有我需要的标题。

1 个答案:

答案 0 :(得分:0)

不确定标题,但combobox中的项目应添加为

while (sqlReader.Read())
{
    comboBox1.Items.Add(new Item(sqlReader["GeneName"].ToString(), sqlReader["Geneid"].ToString()));
}

或(在组合框中显示文字和ID)

while (sqlReader.Read())
{
    comboBox1.Items.Add(new Item(sqlReader["GeneName"].ToString()  + ‘ ‘  + sqlReader["Geneid"].ToString(), sqlReader["Geneid"].ToString()));
}
相关问题