Entity Framework - Casting the retrieved Combobox value to string - c#

Using Entity Framework, I have a Combobox showing a list of data retrieved from a database.
using System; //I removed the other using statements here to preserve space
namespace ExTea_BackEnd
{
public partial class frmAddBreakdown : Form
{
ExTeaEntities Breakdowns;
Breakdown_Type BreakdownTypes;
public frmAddBreakdown()
{
InitializeComponent();
}
private void cmbBreakdownType_SelectedIndexChanged(object sender, EventArgs e)
{
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
string selectedBreakdownTypeId = breakdownType.BrkdwnId;
IQueryable<Breakdown_Type> breakdownTypeQuery = from t in Breakdowns.Breakdown_Types
where t.BrkdwnId == selectedBreakdownTypeId
select t;
List<Breakdown_Type> selectedBreakdownId = breakdownTypeQuery.ToList();
if (selectedBreakdownId != null && selectedBreakdownId.Count > 0)
{
BreakdownTypes = selectedBreakdownId.First();
txtBreakdownId.Text = BreakdownTypes.BrkdwnId.ToString();
}
else
{
BreakdownTypes = null;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Breakdown newBreakdown = new Breakdown();
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
newBreakdown.BrkdwnType = breakdownType.ToString(); //this is where the error occurs
newBreakdown.MachineId = txtMachineId.Text.Trim();
newBreakdown.MachineType = txtMachineType.Text.Trim();
newBreakdown.ReportedDate = dtpDate.Value;
newBreakdown.JobStatus = "I";
Breakdowns.AddToBreakdowns(newBreakdown);
int rowsAffected = Breakdowns.SaveChanges();
if (rowsAffected > 0)
{
MessageBox.Show(rowsAffected + " records added!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! " + ex.Message);
}
}
}
}
I'm trying to save the data in the form back to the database, an error occurs when trying to cast the value selected from the Combobox. Even when I've casted it to the right type, it does not save the selected value! But this,
I'm clueless on what I'm doing wrong here? Can anyone please tell me how to correct this?
Thank you.

newBreakdown.BrkdwnType = breakdownType.ToString();
Here you are just calling .ToString() Method of your object, so it is returning the Type Name, which you are able to view in database table record, for getting the BrkDwnType Property value you should change statement to
newBreakdown.BrkdwnType = breakdownType.BrkdwnType;

it should just be:
newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString();
no need for casting selectedItem if you just want the string value. From a design point of view, you should probably normalize your database and use an ID for breakDownType that references another table with BreakDown types.

Related

Error doesn't let me update data into my database

Error: Invalid column name 'Id'.'
I've been trying to make an update function, the logic behind it I think is fine, but it keeps throwing me this error mentioned above.
internal static void Uredi(Zahtjev odabraniZapis)
{
DB.OpenConnection();
string sql = $"UPDATE Zahtjev_za_nabavu SET Ponuda = '{odabraniZapis.Ponuda}', Opis_predmeta = '{odabraniZapis.Opis_predmeta}', Cijena = '{odabraniZapis.Cijena}', ID_zaposlenika = {odabraniZapis.ID_zaposlenika} WHERE ID_zahtjeva = {odabraniZapis.ID_zahtjeva};";
DB.ExecuteCommand(sql);
DB.CloseConnection();
}
This above is the function that I call to Update existing data.
I get the row that i want to change through ID_zahtjeva .
And this is the function that calls the UPDATE function.
private void btnAzuriraj_Click(object sender, EventArgs e)
{
Zahtjev noviZahtjev = new Zahtjev(int.Parse(txtZahtjev.Text), txtPonuda.Text, txtOpis.Text, txtCijena.Text, int.Parse(txtZaposlenik.Text));
var provjera = ZahtjeviRepository.GetZahtjevi(noviZahtjev.ID_zahtjeva);
if(provjera == null)
{
ZahtjeviRepository.Kreiraj(noviZahtjev);
this.Close();
}
else
{
ZahtjeviRepository.Uredi(noviZahtjev);
this.Close();
}
}

Not sure why this Radio Button is throwing an error?

I am currently making a fitness class booking system for some study I am doing so please bare with me.
I have done most of the code but I am having this strange issue with my 2nd radio button for selecting what class you want.
I have set up my code so a message box appears if the Member ID you have entered is already registered to the fitness class you have selected. For my RadioButton1 (rbCardioClass) and RadioButton2 (rbPilatesClass), the error message box works great and works as it should. But my RadioButton2 (rbSpinClass) will make the error message box appear everytime, even if the MemberID is not associated to the 'Spin Class'.
I have tried different uses of if statements, different radio buttons etc but can't seem to get it to work the way I want.
If I go to my servicesErrorCheck(string[] description)method and just the temp variable to true all radio buttons save to the database table correctly BUT I then lose my erroring, which makes me thinks it is something to do with the way I have set up the message box, maybe.
Here is a screenshot of the prototype form just for reference. FitnessClassBooking Form
Here is a screenshot of the table while the app is running App Running Fitness Form
Here is the error being thrown with MemberID that has no 'Spin' class associated with it App Running Error
Here is my code in question -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace Membership_Formv2
{
public partial class FitnessClassBooking : Form
{
public FitnessClassBooking()
{
InitializeComponent();
}
private void bMainMenu_Click(object sender, EventArgs e)
{
new MainMenu().Show();
this.Hide();
}
private void fitnessInformationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.fitnessInformationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.databaseDataSet);
}
private void FitnessClassBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.databaseDataSet.Members);
// TODO: This line of code loads data into the 'databaseDataSet.FitnessInformation' table. You can move, or remove it, as needed.
this.fitnessInformationTableAdapter.Fill(this.databaseDataSet.FitnessInformation);
}
private void fitnessInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string descriptionfit()
{
string className = "";
if (rbCardioClass.Checked == true)
{
className = "Cardio";
}
else if (rbSpinClass.Checked == true)
{
className = "Spin";
}
else if (rbPilatesClass.Checked == true)
{
className = "Pilates";
}
return className;
}
private string classDescription()
{
string serviceSeletionString = "Class";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
return serviceSeletionString;
}
private bool errorCheckingID()
{
bool statusDB = true;
//Getting row info from MembersTa table
DatabaseDataSet.MembersRow newEntry = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox3.Text));
//Getting information from BookingTa table
if (newEntry == null)
{
statusDB = false;
return (statusDB);
}
return (statusDB);
}
public bool servicesErrorCheck(string[] description)
{
bool temp = true;
string serviceSeletionString = "";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
for (int t = 0; t < description.Length; t++)
{
if (serviceSeletionString.Contains(description[t].Trim()))
{
temp = false;
break;
}
}
return (temp);
}
private string originalaccesdb()
{
string a = "";
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = descriptionfit();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
return a;
}
private string[] accessDB()
{
int t = 0;
int temp;
string[] servicesList = { "n", "n", "n" }; //This variable will store the data
//Same code too extract table information
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox3.Text))
{
//Store inside the array all the services/description against the ID.
//Note that this array will remain "" for all the elements inside the array
//if no descritopn/services (i.e., record) is found against the input ID
servicesList[t] = r["Description"].ToString();
t = t + 1;
}
}
return (servicesList);
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
textBox1.Text = "";
int a = Int32.Parse(textBox2.Text);
DatabaseDataSet.MembersRow newID = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox2.Text));
string booking = "";
int temp;
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox2.Text))
{
booking = r["Description"].ToString() + ", " + booking;
}
}
textBox1.Text = "Member ID is: " + (newID.MemberID).ToString() + Environment.NewLine +
"First Name is: " + (newID.First_Name).ToString() + Environment.NewLine +
"Last Name is: " + (newID.Last_Name).ToString() + Environment.NewLine +
"Bookings: " + booking;
}
public void button2_Click(object sender, EventArgs e)
{
bool status1, status2;
string[] description;
//Error control at the outer level for valid ID
status1 = errorCheckingID();
//Proceed only if ID is valid or status1 is true
if (status1)
{
//Retrieve information from the other database. Ideally you want this method to return
//an array containing registered services. This would be an array of strings.
description = accessDB();
//Services error checking
status2 = servicesErrorCheck(description);
//Now this is the code that would call the method to save data ito database
//when status2 and 2 are true
if (status2)
{
//Code for saving into database.
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = classDescription();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
}
else
{
//Show error that this service is not available
MessageBox.Show("This Class is already assigned to that Member ID");
}
}
else
{
//Error message invalid ID
MessageBox.Show("Invalid ID");
}
}
private void radioButton1_Click(object sender, EventArgs e)
{
}
private void radioButton4_Click(object sender, EventArgs e)
{
}
private void radioButton3_Click(object sender, EventArgs e)
{
}
}
}
I am really not sure why this is happening so I would really appreciate any help.
You are checking each string in descriptions as follows:
serviceSeletionString.Contains(description[t].Trim())
which considering at least one of the strings is just n it will always match Spin.
Quite why you are always returning an array with the blank ones having n, I don't know. Personally I would just use a List<string> and Add each item from the database to it. But that is a separate point.
Either change it to serviceSeletionString == description[t] (don't see why you need Trim()) or just replace the whole foreach loop with description.Contains(serviceSeletionString)

RowUniqueID in filtered row

could somebody help me in C# programing in an web application. Namely, how can we find out RecordUniqueId of the filtered row....in order to further edit (i.e., set values in some other columns in the same row), based on RecordUniqueId value? Or, is it possible to, upon clicking on enter button in order to search for certain row, to immediately have some actions performed on the values in some other columns of filtered row? Let me say in other words, to have some kind of automation of editing values in some other columns of the filtered row?
Thanks in advance
public class PartyVuk2010GENTableControlRow : BasePartyVuk2010GENTableControlRow
{
}
public class PartyVuk2010GENTableControl : BasePartyVuk2010GENTableControl
{
public override void MarkDiscontinued_Click(object sender, ImageClickEventArgs args)
{
try {
DbUtils.StartTransaction();
foreach (PartyVuk2010GENTableControlRow rc in this.GetSelectedRecordControls()) {
PartyVuk2010GENRecord rec;
rec = PartyVuk2010GENTable.GetRecord(rc.RecordUniqueId, true);
if (rec != null) {
rec.Discontinued = true;
rec.Test = "10";
rec.BallotOrder = PartyVuk2010GENTable.Instance.GetLargest()+1;
rec.Save();
}
}
DbUtils.CommitTransaction();
}
catch (Exception ex) {
BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
}
finally {
DbUtils.EndTransaction();
}
this.DataChanged = true;
}

Check if record already exists within the database

I have a program that allows users to enter in movies and details about that movie and store them in a database. I have the database being displayed in my C# program and the user can select one of the rows and the information from that row will be put into the text box it corresponds to, for example the Title will go in the title text box and so on. what I want to do is stop the user hitting the submit button and putting the same record in the database.
Any help would be appreciated
Submit button:
private void btnSubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtTitle.Text) || string.IsNullOrWhiteSpace(txtRunTime.Text))
{
MessageBox.Show("Fill in all the required fields");
}
else
{
if (lstStatus.SelectedIndex == 0)
{
Status = "Watched";
}
else
{
Status = "Not Watched";
}
if (lstType.SelectedIndex == 0)
{
Type = "Movie";
}
else
{
Type = "TV Show";
}
con.Open();
SqlCommand cmd = new SqlCommand("insert into dbo.Movies(Title, Genre, RunTime, Type, Status) values('"+txtTitle.Text+"','"+txtGenre.Text+"','"+txtRunTime.Text+"','"+Type+"','"+Status+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data transferred into the database!");
con.Close();
txtTitle.Text = "";
txtRunTime.Text = ""; /
}
}
Code when selecting a row:
private void DataGridMovies_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if(DataGridMovies.CurrentRow.Index == DataGridMovies.Rows.Count - 1)
{
MessageBox.Show("Empty row selected"); // Display a message to the user
}
else
{
ID = Convert.ToInt32(DataGridMovies.Rows[e.RowIndex].Cells[0].Value.ToString());
txtTitle.Text = DataGridMovies.Rows[e.RowIndex].Cells[1].Value.ToString();
txtGenre.Text = DataGridMovies.Rows[e.RowIndex].Cells[2].Value.ToString();
txtRunTime.Text = DataGridMovies.Rows[e.RowIndex].Cells[3].Value.ToString();
if (DataGridMovies.Rows[e.RowIndex].Cells[4].Value.ToString() == "Movie")
{
lstType.SelectedIndex = 0;
}
else
{
lstType.SelectedIndex = 1;
}// End of IF ELSE Statement
if (DataGridMovies.Rows[e.RowIndex].Cells[5].Value.ToString() == "Watched")
{
lstStatus.SelectedIndex = 0;
}
else
{
lstStatus.SelectedIndex = 1;
}// End of IF ELSE Statement
}//End of IF statement
You need to use sql parameters or your sql database can be hacked.
You can read about that here:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8
cmd.Parameters.AddWith(name, value)
Determine if the record exists. If it does not you are adding it with insert. If not you update the record instead.
Depending on the process power you have at your disposal you might also look into autocomplete. This can hide the fact they are just updating a record you already "found".
https://www.grapecity.com/blogs/dynamic-autocomplete-c1textbox
Meta tagging and algorithms on the back end sometimes take care of duplicate entries.

Sign up using Entity Framework

So i try to create a sign up method using entity framework and c#, this is the method :
//Button create new account
private void BtnSignUp_Click(object sender, EventArgs e)
{
IEnumerable<DriverAcount> list = from a in context.DriverAcounts select a;
foreach (var Ac in list)
{
if (TxBoxNewUserName.Text != Ac.Login)
{
if (TxtBoxPASS1.Text == TxBoxPass.Text)
{
Ac.Login = TxBoxNewUserName.Text;
Ac.Password = TxtBoxPASS1.Text;
context.DriverAcounts.Add(Ac);
MessageBox.Show("the account is create succefuly");
TxBoxNewUserName.Text = "";
TxtBoxPASS1.Text = "";
TxBoxPass.Text = "";
break;
}
else
{
MessageBox.Show("the two passwords didn't matched");
}
TxBoxNewUserName.Text = "";
TxtBoxPASS1.Text = "";
TxBoxPass.Text = "";
continue;
}
else
{
MessageBox.Show("this username is already exist, please choose another one");
TxBoxNewUserName.Text = "";
TxtBoxPASS1.Text = "";
TxBoxPass.Text = "";
break;
}
}
context.SaveChanges();
}
the problem is when i want to add a new user normally it should looking if it exist in database or not, but it didn't do it right, for example if we have two names in DB name1 and name2 and into the TextBox we have name2 it will add the name2 in DB even if it is already exist.
So plz if someone have an idea i will be very appreciate.
You need to look at your code again and understand exactly what it's doing - have you attached the debugger and stepped through it? The driver name will always be created on the first iteration of the foreach loop if the first name retrieved doesn't match the one in the text box. All the others will be ignored.
You can try this instead. There's no need querying for all the records (like you're doing at the moment) when you only want to check if one already exists.
private void BtnSignUp_Click(object sender, EventArgs e)
{
// This performs a case sensitive match on the login name, you'll need to change it if you want to ignore case
DriverAcount existingAccount = context.DriverAcounts.FirstOrDefault(d => d.Login == TxBoxNewUserName.Text);
if (existingAccount != null)
{
MessageBox.Show("This username already exists, please choose another one.");
}
else
{
if (TxtBoxPASS1.Text == TxBoxPass.Text)
{
Ac.Login = TxBoxNewUserName.Text;
Ac.Password = TxtBoxPASS1.Text;
context.DriverAcounts.Add(Ac);
// Only need to call this if you've made changes, so I've moved it here
context.SaveChanges();
MessageBox.Show("The account was created successfully");
}
else
{
MessageBox.Show("The two passwords didn't match each other.");
}
}
TxBoxNewUserName.Text = "";
TxtBoxPASS1.Text = "";
TxBoxPass.Text = "";
}

Categories