[英]Fetch data from database into combo box and its value C#
Good Day, I have a table in my database Class 美好的一天,我的数据库类中有一个表
classid | class
1 JSS 1
2 JSS 2
3 JSS 3
4 SSS 1
5 SSS 2
6 SSS 3
In my combo box, i fetched the class column and set its value to class id, but now when the form loads, its only showing JSS 1 in the combo box leaving JSS 2 - SSS 3. 在组合框中,我获取了class列并将其值设置为class id,但是现在在加载表单时,其仅在组合框中显示JSS 1,而留下JSS 2-SSS 3。
this is my Code 这是我的代码
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; }
}
}
You don't have a loop for reading values from the database: 您没有从数据库读取值的循环:
if (readClass.Read())
{
ClassList.Add(new AddValue(readClass.GetString(1), readClass.GetInt32(0)));
}
should be: 应该:
while (readClass.Read())
{
ClassList.Add(new AddValue(readClass.GetString(1), readClass.GetInt32(0)));
}
Try this:- 尝试这个:-
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.