[英]Fetch data from database into combo box and its value C#
美好的一天,我的數據庫類中有一個表
classid | class
1 JSS 1
2 JSS 2
3 JSS 3
4 SSS 1
5 SSS 2
6 SSS 3
在組合框中,我獲取了class列並將其值設置為class 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; }
}
}
您沒有從數據庫讀取值的循環:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.