SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connecton1"].ConnectionString);
conn.Open();
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial="+Convert.ToInt32(Serialtxt.Text).ToString()+"", conn);
string checker = check.ExecuteReader();
I'm trying to look for a piece of data in my database and assign it to a variable. The error I get is
Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to string
What am I doing wrong?
You have to use ExecuteScalar
instead.
string checker = (string)check.ExecuteScalar();
You should also use sql-parameters to prevent sql-injection.
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial = @Serial", conn);
check.Parameters.AddWithValue("@Serial", Convert.ToInt32(Serialtxt.Text));
If you instead expect multiple rows per serial you can use ExecuteReader
and fill a List<string>
:
List<string> allLocations = new List<string>();
using(SqlDataReader rd = check.ExecuteReader())
while(rd.Read())
allLocations.Add(rd.GetString(0));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments