1

I've been trying to load an INT from my SQL-Server DB into my C# application and convert it into string.

Basically, it's the ID/Primary key of the DB Table that I want to use as string. This is what I do :

string Variable_ID;
Variable_ID = HandleDBNull(reader, "ID");

and I get a IndexOutOfRange exception.

Here is the HandleDBNullfunction :

    private string HandleDBNull(SqlDataReader r, string columnName)
    {
        if (!r.IsDBNull(r.GetOrdinal(columnName)))
            return r[columnName].ToString();
        else 
            return String.Empty;
    }

It works for the string columns so there seems to be something wrong with the conversion. I've already tried Convert.ToString and got the same error.

Any ideas?

1
  • 3
    isDBNull is a bad method-name. It suggests that it returns a bool. Commented Oct 4, 2012 at 9:37

3 Answers 3

3

I would guess that your columnName and columnOrder are out of step with each-other. One is wrong. Since they express the same information, one is redundant. I would use instead:

// probably should be renamed, btw
private string isDBNull(SqlDataReader r, int columnOrder)
{
    if (!r.IsDBNull(columnOrder))
    {
        return r[columnOrder].ToString();
    }
    else return "";
}

obviously with:

Variable_ID = isDBNull(reader, 0);

although I'm not quite sure I'd want everything as strings.

Sign up to request clarification or add additional context in comments.

2 Comments

Please check my edited code. I do not understand why your example works but what I'm trying to do doesn't.
@hermann sounds to me like the column name is not what you think it is. Look at r.GetName(0)
2

You can try with - Because your condition is based on columnOrder

 ... 
 return r[columnOrder].ToString();

Suggestion

private bool isDBNull(SqlDataReader r, string columnName, int columnOrder)
    {
        if (!r.IsDBNull(columnOrder))
        {
            return true;
        }
        return false;
    }

Comments

1

Simplify the code:

string Variable_ID;
Variable_ID = isDBNull(reader, "ID");

private string isDBNull(SqlDataReader r, string columnName)
{
    if (!r.IsDBNull(r.GetOrdinal(columnName)))
        return r[columnName].ToString();
    else 
        return string.Empty;
}

3 Comments

Thanks, one less parameter now. Original problem persists though.
Same content replaced in question but no UpVote :(
On which line or function are you getting the exception exactly.

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.