1

我有个问题。我无法将组合框中的选定数据保存到数据库中。任何人都可以提供任何意见或为什么会这样?

以下是使大家能够更多地了解我的问题的代码:

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");
        }
    }

任何帮助将不胜感激。谢谢!

4

1 回答 1

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;
于 2012-07-31T03:33:18.107 回答