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

本文关键字:组合 数据 数据库 提取 | 更新日期: 2023-09-27 18:31:27

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

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; }
        }
    }

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

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

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)));
}

试试这个:-

   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);
    }
}