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 メソッドで、なぜSelectedIndexls.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 に答える