There are a few problems with lines 20-22
The first problem is line 20 itself; it is a textbook case of a
SQL Injection Vulnerability
.
NEVER EVER should an SQL query be created concatenating by together commands and variables. The proper thing to use is a
SQL Parameter[
^]. You replace the variable with placeholder and you add to the commands Parameter collection to assign the value to the placeholder.
string checkuser = "SELECT * FROM register where [USERNAME] = @User";
SqlCommand com = new SqlCommand(checkuser,conn);
com.Parameters.AddWithValue("@User", TextBoxunm.Text);
The second problem is the query does not seem to be right for what you are wanting to do. It looks like you simply want check to see if a user name is valid.
The query you wrote will return everything about the user BUT only if that user is found.
1. If the user is found you return the entire matching record. The first column is probably a numerical primary key or identity. So your code seems to work fine.
2. If a user is not found, then SQL will return a
NULL.
Thus the error
The solution is simple; change EITHER the query OR the method used.
Changing the SQL Query is the most efficient way for both the database and the application.
string checkuser = "SELECT Count(*) FROM register where [USERNAME] = @User";
The other way is less efficient as the DB will still be returning a full record and pass that to the application. But it is a viable alternative
int temp = com.ExecuteNonQuery();