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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.