比较数组和创建数据到数据库

时间:2012-07-30 01:34:20

标签: c# arrays linq

我现在卡在阵列比较和创建它。我有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();
        }
    }

1 个答案:

答案 0 :(得分: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();

现在使用conbobox的SelectedValue属性而不是您将获得的SelectedIndex属性 与站名相关的站ID。

 TS.stationID = cbStation.SelectedValue;

同样的事情也是位置

你也可以在这里使用数组代替。