从数据库中获取数据到组合框及其值C#

时间:2014-11-21 12:36:10

标签: c# windows

美好的一天,我的数据库中有一个表 Class

classid | class
1         JSS 1
2         JSS 2
3         JSS 3
4         SSS 1
5         SSS 2
6         SSS 3

在我的组合框中,我获取了类列并将其值设置为类id,但是现在当表单加载时,它只在组合框中显示JSS 1而离开JSS 2 - SSS 3。

这是我的代码

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Solutions\Desktop\My Work\ExamProject\Project DataBase File For Exam\EExamDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
bool classHaveBeenAdded = false;

void ClassCombo()       
        try
        {
            con = new SqlConnection(Properties.Settings.Default.MyConnection);
            cmd = new SqlCommand("SELECT * FROM Classes", con);
            cmd.Connection.Open();
            SqlDataReader readClass = cmd.ExecuteReader();
            ArrayList ClassList = new ArrayList();
            if (readClass.Read())
            {
                ClassList.Add(new AddValue(readClass.GetString(1), readClass.GetInt32(0)));
            }
            readClass.Close();
            cmd.Connection.Close();

            this.comboBoxClassID.DataSource = ClassList;
            this.comboBoxClassID.DisplayMember = "Display";
            this.comboBoxClassID.ValueMember = "Value";
            classHaveBeenAdded = true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public class AddValue
    {
        public string m_Display;
        public int m_Value;

        public AddValue(string Display, int Value)
        {
            m_Display = Display;
            m_Value = Value;
        }

        public string Display
        {
            get { return m_Display; }
        }

        public int Value
        {
            get { return m_Value; }
        }
    }

2 个答案:

答案 0 :(得分:1)

您没有从数据库中读取值的循环:

if (readClass.Read())
{
    ClassList.Add(new AddValue(readClass.GetString(1), readClass.GetInt32(0)));
}

应该是:

while (readClass.Read())
{
    ClassList.Add(new AddValue(readClass.GetString(1), readClass.GetInt32(0)));
}

答案 1 :(得分:0)

试试这个: -

   void ClassCombo()       
    try
    {
        con = new SqlConnection(Properties.Settings.Default.MyConnection);
        cmd = new SqlCommand("SELECT * FROM Classes", con);
        cmd.Connection.Open();
        SqlDataReader readClass = cmd.ExecuteReader();
        ArrayList ClassList = new ArrayList();
        int i=0;
        while (readClass.Read())
        {
            ClassList.Add(readClass["class"].ToString());
            i++;
        }
        readClass.Close();
        cmd.Connection.Close();

        this.comboBoxClassID.DataSource = ClassList;
        this.comboBoxClassID.DisplayMember = "Display";
        this.comboBoxClassID.ValueMember = "Value";
        classHaveBeenAdded = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}