check if returns anything.
hi! can anybody please help me. Given the code below how can i check if it does returns anything.
Code:
string SqlConnStr = Properties.Settings.Default.MyConnString;
sqlConn = new SqlConnection(SqlConnStr);
sqlConn.Open();
qryStr = "Select username from users where username = '" + txtNewUsername.Text.ToUpper() + "'";
SqlCommand sqlCmd = new SqlCommand(qryStr, sqlConn);
object result = sqlCmd.ExecuteScalar();
Thanks advance!!!
Re: check if returns anything.
You've already got the user name so you don't need to retrieve it. Use:
Code:
qryStr = "SELECT COUNT(*) FROM users WHERE username = @username";
SqlCommand sqlCmd = new SqlCommand(qryStr, sqlConn);
sqlCmd.Parameters.AddWithValue("@username", txtNewUsername.Text.Trim());
if ((int)sqlCmd.ExecuteScalar() == 0)
{
// No matching rows so user name doesn't exist.
}
else
{
// At least one matching row.
}
Re: check if returns anything.
no, im just trying to check if the value from txtnewusername.text is already in the database that's why i want to execute that query and if it returns value then the username from txtnewusername is already in the database so i will warn the user that the username he/she entered is already in the database. that's the purpose of me why i check if it returns something. btw, i'v try your code but it gives me an error saying
Quote:
Specified cast is not valid.
Code:
if ((int)sqlCmd.ExecuteScalar() == 0) //ERROR here
{
MessageBox.Show("UserName Already exist.", "Add User", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtNewUsername.Focus();
}
Re: check if returns anything.
I know the purpose of what you're doing but I'm saying that you don't need to retrieve the user name to do it. What you care about is the number of matching records. Zero means it doesn't exist and greater than zero means it does. If you do that then you don't have to check whether anything is returned or not because you know it will be. You just have to test its value. You shouldn't be getting that error with my code. Did you change the SQL code to use COUNT(*)?
Re: check if returns anything.
Oic...Thanks i got it! i forgot to use the COUNT(*).