0

我现在对数组比较和创建它感到困惑。我有 2 张桌子,车站和位置。站内的列是 id 和站名。位置表相同,唯一不同的是名称。我将 id 放入数组中,并将名称放入数组中。我想比较名称和 id,以便当用户选择名称时,程序知道哪个 id 属于所选名称,并使用它们的主键将其保存到另一个表中。这是我从现在开始创建的代码,但我不知道如何解决它。希望我能在这里得到一些帮助。谢谢!

private void btnCreate_Click(object sender, EventArgs e)
    {
        using (testEntities Setupctx = new testEntities())
        {
            string[] stations = StationNameList();
            int[] stationsID = StationIDList();
            string[] locations = LocationNameList();
            int[] locationsID = LocationIDList();

            int Stationindex = cbStation.SelectedIndex;
            int Locationindex = cbLocation.SelectedIndex;

            trolleyservice TS = new trolleyservice();
            TS.stationID = cbStation.SelectedIndex;
            TS.locationID = cbLocation.SelectedIndex;
            TS.tServiceTiming = txtTime.Text;
            TS.tServiceType = txtType.Text;
            Setupctx.trolleyservices.AddObject(TS);
            txtTime.Text = "";
            txtType.Text = "";

            MessageBox.Show("New Trolley Service Has Been Created.");
        }
    }

这是我为每个表创建的所有数组。

 private string[] StationNameList()
    {
        using (testEntities Setupctx = new testEntities())
        {
            return Setupctx.stations.Select(s => s.Station1).OrderBy(s => s).ToArray();

        }
    }

    private int[] StationIDList()
    {
        using (testEntities Setupctx = new testEntities())
        {
            return Setupctx.stations.Select(sid => sid.idstations).OrderBy(sid => sid).ToArray();
        }
    }

    private string[] LocationNameList()
    {
        using (testEntities Setupctx = new testEntities())
        {
            return Setupctx.locations.Select(l => l.Location1).OrderBy(l => l).ToArray();
        }
    }

    private int[] LocationIDList()
    {
        using (testEntities Setupctx = new testEntities())
        {
            return Setupctx.locations.Select(lid => lid.idlocation).OrderBy(lid => lid).ToArray();
        }
    }
4

1 回答 1

0

在这里你可以做的事情,而不是取两个不同的名称和 ID 数组,你可以像这样获取站类列表。

 private List<stations> StationNameList()
  {
    using (testEntities Setupctx = new testEntities())
    {
        return Setupctx.stations.OrderBy(s => s.Station1).ToList();
    }
  }

现在将此列表分配给 cbStation 作为这样的数据源

cbStation.DataSource =StationNameList() ;
cbStation.DataTextField = "Station1";//it is text field that you want to display
cbStation.DataValueField = "idstations";//it is value field of combo box
cbStation.DataBind();

现在使用组合框的 SelectedValue 属性而不是 SelectedIndex 属性,您将获得与电台名称相关的电台 ID。

 TS.stationID = cbStation.SelectedValue;

同样的事情也适用于位置

您也可以在此处使用数组代替列表。

于 2012-07-30T04:52:52.857 回答