I have a problem. I can’t save the selected data from the combo box into a database. Can anyone provide any opinion or why it’s like that?
Here are the codes that enables you all to understand more about my problem:
private void Create_LS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
cbStation.DisplayMember = "StationName";
cbStation.ValueMember = "StationID";
cbStation.DataSource = Setupctx.stations.ToList();
cbLocation.DisplayMember = "LocationName";
cbLocation.ValueMember = "LocationID";
cbLocation.DataSource = Setupctx.locations.ToList();
}
}
private void btnCreate_Click(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
locationstation ls = new locationstation();
ls.stationID = cbStation.SelectedIndex;
ls.locationID = cbLocation.SelectedIndex;
Setupctx.locationstations.AddObject(ls);
Setupctx.SaveChanges();
cbStation.SelectedIndex = -1;
cbLocation.SelectedIndex = -1;
MessageBox.Show("New Location Station Is Created");
}
}
Any help will be greatly appreciated. Thanks!
In your create method, why are you assigning
SelectedIndexto ls.StationID and ls.locationID ? Selected index will give you the index of the selected item. I believe you are interested in SelectedItem or you may use Text Property.EDIT:
Since your StationID and locationID are int, you may Convert the SelectedItem to int before assigning them to the fields. (its better to use int.TryParse to avoid the exception)
or
Then