1

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();
        }
    }
Kevin
  • 1,574
  • 4
  • 19
  • 45

3 Answers3

2

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().

David L
  • 32,885
  • 8
  • 62
  • 93
  • please do never read Data from a Database like that. Have a look at my answer. – swe Jun 01 '15 at 15:08
  • @swe The OP never asked about the CORRECT methodology for retrieving strings from the database but rather how to solve the specific error that he was getting. However, I've updated my answer to the "correct" methodology. – David L Jun 01 '15 at 15:12
1
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.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
0

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.

artplastika
  • 1,972
  • 2
  • 19
  • 38
swe
  • 1,416
  • 16
  • 26