简体   繁体   English

无法将数据保存到数据库

[英]Unable to save Data into a database

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 SelectedIndex to ls.StationID and ls.locationID ? 在您的create方法中,为什么要将SelectedIndex分配给ls.StationID和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. 我相信您对SelectedItem感兴趣,或者您可以使用文本属性。

EDIT: 编辑:

Since your StationID and locationID are int, you may Convert the SelectedItem to int before assigning them to the fields. 由于您的StationID和locationID为int,因此您可以在将它们分配给字段之前将SelectedItem转换为int。 ( its better to use int.TryParse to avoid the exception ) 最好使用int.TryParse以避免异常

int stationID = Convert.ToInt32(cbStation.SelectedItem.ToString());
int locationID = Convert.ToInt32(cbLocation.SelectedItem.ToString());

or 要么

int stationID = Convert.ToInt32(cbStation.Text);
int locationID = Convert.ToInt32(cbLocation.Text);

Then 然后

ls.stationID = stationID;
ls.locationID = locationID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM