I need help getting the result from a SQL select query into a string variable in C#. I’m building a login system where after users log in successfully, I want to check their role from the database and redirect them to different pages. Admin users should go to the admin dashboard and regular users should go to the user dashboard.
Here’s my current login button code:
protected void btnLogin_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT COUNT(*) FROM USER_ACCOUNTS WHERE USERNAME=@USERNAME AND PASS_WORD=@PASS_WORD";
SqlConnection connection = new SqlConnection(connectionStr);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
SqlParameter userParam = new SqlParameter("@USERNAME", SqlDbType.NVarChar, 40);
userParam.Value = txtUsername.Text.Trim();
command.Parameters.Add(userParam);
SqlParameter passParam = new SqlParameter("@PASS_WORD", SqlDbType.NVarChar, 60);
passParam.Value = txtPassword.Text.Trim();
command.Parameters.Add(passParam);
connection.Open();
int loginResult = (Int32)command.ExecuteScalar();
}
This is where I’m stuck:
if (loginResult >= 1)
{
string roleQuery = "SELECT USER_TYPE FROM USER_ACCOUNTS WHERE USERNAME=@USERNAME";
if (userRole == "MEMBER")
{
Session.Add("username", txtUsername.Text);
Response.Redirect("~/MEMBER_PAGES/MemberDashboard.aspx");
}
else if (userRole == "ADMINISTRATOR")
{
Session.Add("username", txtUsername.Text);
Response.Redirect("~/ADMIN_PAGES/AdminPanel.aspx");
}
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "error", "<script>alert('Login failed - wrong credentials')</script>");
}
}
How do I properly execute the second query and store the role value in the userRole variable?