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 = "";
}
Related
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)
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.
I'm new about C#, I learnt C programmation for one year now.
I created a Window Form which asks the user to complete a registration form.
My registration form
I'd like to display an error message below the buttons when a field is not filled or a field isn't well used.
I used this basic code :
private void button1_Click(object sender, EventArgs e)
{
if (!isOkay(userTextBox.Text))
{
label5.Text = "Please, enter an username.";
label5.Visible = true;
}
else if (!isOkay(mailTextBox.Text))
{
label5.Text = "Please, enter a mail address.";
label5.Visible = true;
}
else if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
{
label5.Text = "Please, match both mails addresses.";
label5.Visible = true;
}
else if (!isOkay(passwordTextBox.Text))
{
label5.Text = "Please, enter a password.";
label5.Visible = true;
}
else
{
label5.Text = "Valid form, yay !";
label5.Visible = true;
}
}
private Boolean isOkay(string textBoxContent)
{
return (textBoxContent.Length > 0 || textBoxContent.Equals(null));
}
Are there any elegant or optimized ways to do it properly ? I found some Error providers, but apparently error providers open a pop-up, and I just want a "red error message below buttons".
Can you give me some help ? :)
Given a class like this
public class RequiredFieldsError
{
private List<string> errors;
public RequiredFieldsError()
{
errors = new List<string>();
}
public int Count
{
get{return errors.Count;}
}
public void AddField(string errorField)
{
errors.Add(errorField);
}
public override string ToString()
{
if(errors.Count == 0)
return string.Empty;
else
{
string fields = string.Join(Environment.NewLine, errors);
fields = "The following fields contains errors:" + Environment.NewLine + fields;
return fields;
}
}
}
then you could change your code to
private void button1_Click(object sender, EventArgs e)
{
RequiredFieldsError rfe = new RequiredFieldsError();
if (!isOkay(userTextBox.Text))
rfe.AddField("User name missing, Please, enter an username.";
if (!isOkay(mailTextBox.Text))
rfe.AddField("Email address missing, Please, enter a mail address.";
if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
rfe.AddField("Email address doesn't match the confirmation email");
if (!isOkay(passwordTextBox.Text))
rfe.AddField("Password missing, Please, enter a password.";
if(rfe.Count > 0)
{
// MessageBox.Show(rfe.ToString());
label5.Text = rfe.ToString()
label5.Visible = true;
}
}
This approach avoids the unnerving situation (for your user) when he/she receives an error message, he/she fixes it just to receive another error message at the next attempt to confirm the form.
Of course your label should be tall enough to show all the possible messages or just use a messagebox.
I suggest also to change your IsOkay function to
private Boolean isOkay(string textBoxContent)
{
return !string.IsNullOrWitheSpace(textBoxContent));
}
this will handle also a string composed just of one or more spaces. (not null and not length==0)
You can use ErrorProvider. It show's an error icon after your textbox.
For one of your textboxes for example:
if (!isOkay(userTextBox.Text))
{
errorProvider1.SetError(userTextBox "yourmessage");
}
else{
errorProvider1.Clear();
}
Link: http://www.dotnetperls.com/errorprovider
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.
My previous question is urlrewriter problem: Query string is duplicated shown?
I'm developing asp.net web site. But has a one problem. There is duplicated query string like this www.domainname.com/default.aspx?Query=Value1&Query=Value2
I'm using to too many pages like this Request.QueryString["Query"]. But this return Value1,Value2 . I don't want to fix this problem to too many pages. I want to fix querystring before pageload. I think that Maybe will write some function on global.asax. But i don't know to how write it.
You have a any idea?
I beleive Request.QueryString itself is read-only. You could setup your own collection containing whatever you want to use:
public Dictionary<string, object> qsValues = new Dictionary<string, object>();
foreach (string key in Request.QueryString.Keys) {
if (Request.QueryString[key].Count > 1) {
qsValues[key] = Request.QueryString[key][0];
}
else {
qsValues[key] = Request.QueryString[key];
}
}
Or just access the first entry in the list of values for that query string parameter in your code:
if (Request.QueryString["Query"].Count > 1) {
queryValue = Request.QueryString[0];
}
public static bool bi = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (bi == false)
{
bi = true;
Response.Redirect("MainPage.aspx?id=null");
}
else if (bi)
{
string s = Request.QueryString["id"].ToString();
if (s != "null")
{
switch (s)
{
case "News":
{
ProjectsManagment.Controls.AllNews n = new Controls.AllNews();
MainContentsAsp.Controls.Add(n);
break;
}
default:
break;
}
}
}
}
}