【问题标题】:ComboBox with sections populated from database c#带有从数据库 c# 填充的部分的组合框
【发布时间】:2018-03-21 19:14:32
【问题描述】:

正如标题所示,我正在尝试为其中包含的每种数据类型创建一个具有不同标题的 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,但它们不在一行上,也没有我需要的标题。

【问题讨论】:

  • 假设 WinForms,您将不得不自己研究绘图。请参阅 DrawMode 属性以及 DrawItem 和 MeasureItem 事件。

标签: c# sql visual-studio combobox


【解决方案1】:

不确定标题,但 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()));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多