我有问题。我无法将选定的数据从组合框保存到数据库中。任何人都可以提供任何意见或为什么会这样?
以下代码可让您全面了解我的问题:
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");
}
}
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
在您的create方法中,为什么要将SelectedIndex
分配给ls.StationID和ls.locationID?选定的索引将为您提供所选项目的索引。我相信您对SelectedItem感兴趣,或者您可以使用Text财产。
编辑:
由于您的StationID和locationID是int,因此您可以在将SelectedItem分配给字段之前将其转换为int。 (最好使用int.TryParse来避免异常)
int stationID = Convert.ToInt32(cbStation.SelectedItem.ToString());
int locationID = Convert.ToInt32(cbLocation.SelectedItem.ToString());
或
int stationID = Convert.ToInt32(cbStation.Text);
int locationID = Convert.ToInt32(cbLocation.Text);
然后
ls.stationID = stationID;
ls.locationID = locationID;