Reputation: 249
I have a table named Departmants
, which consist of 4 Fields: DepId
, DepName
, DoctorId
, PatientId
.
I am attempting to populate a combobox control with department names, using the following code:
public void ListDeps(ComboBox comboBox1)
{
DepartmantClass d; //I have created this class with the same fields in the Departmants table
try
{
con = Baglanti.Baglan();
cmdStr = "Select * from Departmants";
cmd = new SqlCommand(cmdStr, con);
if (con.State == ConnectionState.Closed) { con.Open();}
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
d = new Bolumler();
while (reader.Read())
{
d.DepName = reader["DepName"].ToString();
d.DoctorId = Convert.ToInt32(reader["DoctorId"].ToString());
d.DepId= Convert.ToInt32(reader["DepId"].ToString());
comboBox1.Items.Add(d);
}
}
reader.Close();
}
}
private void frmMain_Load(object sender, EventArgs e)
{
DepartmantClass d= new DepartmantClass ();
d.ListDeps(cmbDepNames);
}
Everything is ok. The problem is (I think) I can't pass the values to the combobox
properly.
Because when I execute the following line in the comboBox_SelectedIndexChanged
event handler - I have noticed that all the values are the same.
MessageBox.Show(comboBox1.SelectedItem.ToString());
Upvotes: 0
Views: 45
Reputation: 1301
Swap these
d = new Bolumler();
while (reader.Read())
{
...
to
while (reader.Read())
{
d = new Bolumler();
...
So you create a new instance of Bolumler on each iteration.
Upvotes: 2