1

I have this code:

public void nactiData()
{
        SqlCommand cm = new SqlCommand("SELECT * FROM zajezd WHERE akce="+nc_zajezd_vyber, con); 
        con.Open();
        SqlDataReader reader = cm.ExecuteReader();

        if (reader.Read())
        {
            zpocdnu.Text = reader.GetInt32(31).ToString();
            zcena3.Text = reader.GetDecimal(6).ToString();
        }

        con.Close();
    }

Problem is that it doesn't read zcena3 because the datatype in the table is numeric.

On Microsoft's website is written that I should read it with GetDecimal, but it doesn't work either.

Is there any solution?

7
  • 6
    Using * with column positions is asking for trouble. Write out the column names, like GetString("col1") Commented Jul 6, 2013 at 8:42
  • I tried that, what should replace *? Commented Jul 6, 2013 at 8:45
  • 1
    What exact datatype are those columns in SQL Server? If they are int, smallint or bigint; you need to use .GetInt16/.GetInt32/.GetInt64 (not .GetDecimal). You said using GetDecimal doesn't work - how does it not work? Do you get an error? If so: what error ? Commented Jul 6, 2013 at 8:51
  • Oh, GetDecimal did work, I had nulls allowed. Thanks Commented Jul 6, 2013 at 8:54
  • 1
    @Andomar: it should be reader.GetString(reader.GetOrdinal("col1")) (and typically the result of calling GetOrdinal would be executed only once and then cached in a variable). Commented Jul 6, 2013 at 9:27

1 Answer 1

3

(You've solved your problem yourself, but let me suggest the following.)

Since you are dealing with a SQL Server data reader, use GetSqlDecimal instead of GetDecimal:

  • It should perform a little better (since it doesn't do any unnecessary conversion).
  • It can also deal with NULL (via the IsNull property of the returned SqlDecimal value).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.