Reputation: 1624
I get this message in the following when I try to do this
ThisString= reader["ThisString"];
In the following:
string ThisString;
using (SqlConnection con = new SqlConnection("connectionstring"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table WHERE parameter=@parameter", con))
{
cmd.Parameters.AddWithValue("@parameter", parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
while (reader.Read())
{
ThisString= reader["ThisString"];
}
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Close();
}
}
Upvotes: 1
Views: 2257
Reputation: 33863
You are receiving the error because retrieving an item from reader by string index returns as type object as shown by the following signature:
public override Object this[string name] { get; }
Typically, to easily convert from object to string you would call .ToString()
on the result.
ThisString = reader["ThisString"].ToString();
However, since this is unsafe when working with SqlDataReader as it will not handle Null Reference Exceptions or DBNull, you should use the GetOrdinal() and GetString() methods of your reader.
var ordinal = reader.GetOrdinal("ThisString")
if (ordinal > -1)
{
ThisString = reader.GetString(ordinal);
}
By checking for the ordinal of the column in the data reader, you are ensuring that your target column is present. If the value is -1, it is not present and you should not attempt to call GetString()
.
Upvotes: 2
Reputation: 1455
The sqlReader has methods to read Strings and other strongly typed objects from it.
Try use reader.IsDBNull(ColIndex)
to check for DBNull
Try use reader.GetString(ColIndex)
to read a string from the database
Try use reader.GetOrdinal("ThisString")
to read the ColumnIndex of your column.
Upvotes: 0
Reputation: 223352
ThisString= Convert.ToString(reader["ThisString"]);
That will also save you from Null Reference Exception, In case of DBNull.Value
, you will get an empty string back.
You can also utilize SqlDataReader.GetString
method and specify the column index.
ThisString= reader.GetString(0);//assuimg 0 is the column index
Or use SqlDataReader.GetOridnal
method to get column index, and then use reader.GetString
.
Upvotes: 1