here is my code but its retrieve only last record not all
SqlConnection history= new SqlConnection("Data Source=.;Initial Catalog=db3;Integrated Security=True");
history.Open();
SqlCommand histcmd= new SqlCommand("SELECT salary FROM persontable WHERE (Name = @name)", history);
histcmd.Parameters.AddWithValue("@name", checkname.text);
SqlDataReader DRhistory= histcmd.ExecuteReader();
if (DRhistory.Read())
{
combobox.Text = DRhistory.GetValue(0).ToString();
}
history.Close();
You need a loop if you want to get all:
List<string> salaryList = new List<string>();
while(DRhistory.Read())
{
salaryList.Add(DRhistory.GetString(0));
}
To fill a combobox you can either add them in the loop, simpliest approach:
while(DRhistory.Read())
{
comboBox.Items.Add(DRhistory.GetString(0));
}
or use a BindingSource
which you can assign the list as datasource:
BindingSource bs = new BindingSource();
bs.DataSource = salaryList;
comboBox.DataSource = bs;
As an addition to @TimSchmelters answer:
You also need to populate the ComboBox
with the objects in the List
. Setting the Text
property doesn't add the object to the ComboBoxes
Item
collection.
using(SqlConnection history= new SqlConnection("Data Source=.;Initial Catalog=db3;Integrated Security=True"))
{
history.Open();
SqlCommand histcmd= new SqlCommand("SELECT salary FROM persontable WHERE (Name = @name)", history);
histcmd.Parameters.AddWithValue("@name", checkname.text);
List<string> salaryList = new List<string>();
using (SqlDataReader DRhistory = histcmd.ExecuteReader())
{
while(DRhistory.Read())
{
salaryList.Add(DRhistory.GetString(0));
}
}
combobox.Items.AddRange(salaryList.ToArray());
history.Close();
}
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.