2012-07-13 77 views
1

我不知道如何調用該方法來檢查數據庫是否具有相同的站名稱,如果用戶正在創建它。我設法將數據庫的列存儲到數組中,但仍然無法檢查。有人可以幫我嗎?我有點卡住了。比較陣列與TextBox檢查數據庫中的重複值

這是生成將數據創建到數據庫的按鈕處理程序中的代碼。

private void btnCreate_Click(object sender, EventArgs e) 
    { 
     using (testEntities Setupctx = new testEntities()) 
     { 
      station creStation = new station(); 
      creStation.Station1 = txtStation.Text; 
      creStation.Seats = cbSeats.SelectedItem.ToString(); 
       Setupctx.stations.AddObject(creStation); 
       Setupctx.SaveChanges(); 
       txtStation.Text = ""; 
       cbSeats.SelectedIndex = -1; 
       MessageBox.Show("New Station Has Been Created."); 
     } 
    } 

這是我將列存儲到數組中的代碼。

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

任何人都可以幫忙嗎?對你的幫助表示感謝。

回答

1

如果你想檢查數據庫中是否已經存在電臺,然後在btnCreate_Click之前添加電臺,你可能會從你的方法StationNameList得到一個電臺列表,然後檢查在文本框中輸入的電臺名稱是否已經存在列表。你可以做

private void btnCreate_Click(object sender, EventArgs e) 
    { 
     using (testEntities Setupctx = new testEntities()) 
     { 
     string[] stations = StationNameList(); 

     if(stations.Contains(txtStation.Text)) 
       { 
       //already exists 
       } 
     else 
       { 
       //does not exists 
       //your code to insert the new object 
       } 
     } 
    } 
+0

謝謝!我可以完成它! – Philemon 2012-07-13 09:25:10

0

試試這個

 private void btnCreate_Click(object sender, EventArgs e) 
    { 
     using (testEntities Setupctx = new testEntities()) 
     { 
      station creStation = new station(){Station1=txtStation.Text,Name=NameTextbox.text,Seats = cbSeats.SelectedItem.ToString()}; 
      if (!Setupctx.Stations.Any(st => st.Name == creStation.Name)) 
      { 
       Setupctx.stations.AddObject(creStation); 
       Setupctx.SaveChanges(); 
       txtStation.Text = ""; 
       cbSeats.SelectedIndex = -1; 
       MessageBox.Show("New Station Has Been Created."); 
      } 
     } 
    } 

我希望這會幫助,我希望你在車站類Name屬性,並綁定到一些文本框的UI。