Reputation: 101
I had no idea of how to call out the method to check if the database has the same Station name if the user was creating it. I managed to store the column of the database to array but I still can't get a way to check. Can anybody help me with it? I kinda stuck now.
This is the code in the button handler that generate the creating of data into database.
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.");
}
}
This is the code that I store the column into the Array.
private string[] StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(x => x.Station1).OrderBy(x => x).ToArray();
}
}
Can anyone help? Your help will be greatly appreciated.
Upvotes: 1
Views: 1551
Reputation: 12305
Try this
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.");
}
}
}
I hope this will help , and i expect you has Name property in Station class and is bind to some Textbox in UI.
Upvotes: 0
Reputation: 223287
If you want to check if the station already exist in the data base then in btnCreate_Click
before adding the station you may get a list of stations from your method StationNameList
and then check if the station name entered in the textbox already exists in the list. You can do
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
}
}
}
Upvotes: 1