|
-
Aug 28th, 2006, 10:43 PM
#1
Thread Starter
Fanatic Member
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!!!
-
Aug 28th, 2006, 11:02 PM
#2
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.
}
-
Aug 29th, 2006, 02:48 AM
#3
Thread Starter
Fanatic Member
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
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();
}
Last edited by daimous; Aug 29th, 2006 at 02:52 AM.
-
Aug 29th, 2006, 03:13 AM
#4
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(*)?
-
Aug 29th, 2006, 03:34 AM
#5
Thread Starter
Fanatic Member
Re: check if returns anything.
Oic...Thanks i got it! i forgot to use the COUNT(*).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|