I am trying to display data from a table into a combo box(usernames in a combo box) but i sorted most errors that i got . "my error"
System.InvalidCastException: Specified cast is not valid.
also i only get this message when i debug the program and open that form
my code:
private void add_user_Load(object sender, EventArgs e)
{
DataSet Ds = new DataSet();
// Hide Copy Code
string strConnectionString = "Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(strConnectionString);
using (SqlCommand cmd = new SqlCommand("SELECT [username] FROM [user1]",
objconnection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(Ds);
}
}
var empList = Ds.Tables[0].AsEnumerable().Select(dataRow =>
dataRow.Field<int>("username")).ToList();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.DataSource = empList;
comboBox1.SelectedIndex = 0;
// Hide Copy Code
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedItem.ToString();
}
any help would be much apreciated,thanks in advance
dataRow.Field<int>("username")).ToList();
should be
dataRow.Field<string>("username")).ToList();
you are casting username to int which should be string.
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.