Надеюсь, что этот вопрос имеет смысл ..
По сути, я делаю хирургическую систему для универа.
Я создал базу данных на основе услуг и таблицу пользователей с именем пользователяи пароли и т. д.
Логин все отсортировано.Консоль печатает правильный RoleType и регистрирует пользователя.
Я сумасшедший перечисление под названием RoleType, которое я пытаюсь изменить в зависимости от роли, которую пользователь играет в
Это где я вдо сих пор ...
Форма входа
//Declare an enum to store roletypes
public enum RoleTypes
{
practiceManager,
doctor,
receptionist
}
private void btnLogin_Click(object sender, EventArgs e)
{
//Try and open a connection with database and run the code
try
{
//Create new instance of sql connection, pass in the connection string for BayOneSurgerySystem.mdf to connect to database.
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\davie\Documents\UniWork\Software Engineering\SurgerySystem\SurgeryDatabase\BayOneLoginSystem.mdf;Integrated Security=True;Connect Timeout=30");
//Create new instance of SQlCommand and pass in a query to be called to retrieve table data for username and passwords aswell as the connection object.
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username and Password = @password", conn);
//This passes user input into @username and @password
cmd.Parameters.AddWithValue("@username", txtBoxUsername.Text);
cmd.Parameters.AddWithValue("@password", txtBoxPassword.Text);
//Open connection with database
conn.Open();
//Create new instance of dataSet to hold the data retrieved from sql query
DataSet ds = new DataSet();
//Create new instance of DataAdpater to retrieve the data pass in Sql command
SqlDataAdapter da = new SqlDataAdapter(cmd);
//using DataAdapter fill in dataSet wiht data if user input and stored data matches
da.Fill(ds);
//Close the connection now data table is filled with username and password
conn.Close();
//declare bool, true if there is a match with database and user input
bool loginSuccess = (ds.Tables[0].Rows.Count == 1);
//if login success is true then open menu
if (loginSuccess)
{
//Change state of enum RoleTypes bases on result from dataSet Role column.
Console.WriteLine(ds.Tables[0].Rows[0]["Role"].ToString());
try
{
switch (ds.Tables[0].Rows[0]["Role"])
{
case "Doctor":
{
RoleTypes roleType = RoleTypes.doctor;
Console.WriteLine("Role type chnage to" + roleType.ToString());
}
break;
case "Practice Manager":
{
RoleTypes roleType = RoleTypes.practiceManager;
Console.WriteLine("Role type chnage to" + roleType.ToString());
}
break;
case "receptionist":
{
RoleTypes roleType = RoleTypes.receptionist;
Console.WriteLine("Role type chnage to" + roleType.ToString());
}
break;
default:
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Logged in.");
FrmMenu menu = new FrmMenu();
this.Close();
menu.Show();
}
else
{
MessageBox.Show("Invalid username or password.", "Error!", MessageBoxButtons.RetryCancel);
Console.WriteLine("Not logged in");
}
}
//If connection cant be opened diplsay error message and catch exception and print to console
catch(Exception ex)
{
Console.WriteLine(ex);
MessageBox.Show("Sorry can't connect");
}
}
}
}
Идея состоит в том, что на общедоступный enum можно ссылаться в FrmMenu и других элементах управлениябудет видимым на основе перечисления.
Это просто игнорирование tryCatch с оператором switch и не перехватывает никаких исключений?Есть идеи почему?или если есть гораздо более эффективный способ сделать это?
Заранее спасибо!