1

I have SqlDataReader which fills multiple textboxes, but the issue is when they are NULL I get an exception which I dont know how to handle.

 SqlCommand command = new SqlCommand("SELECT * FROM zajezd WHERE akce='" + akce + "' and rocnik='" + klientClass.Rocnik() + "'", spojeni);
                spojeni.Open();
                SqlDataReader read= command .ExecuteReader();

                if (read.Read())
                {

                s_ub_cen.Text = read.GetDecimal(59).ToString();
                object nulldate = (s_ub_dat.Text = read.IsDBNull(61) ?
                    string.Empty : read.GetDateTime(61).ToShortDateString());
 }

Exception: System.Data.SqlTypes.SqlNullValueException: Data are null.

I have like 20 Textboxes, is there any easy solution? I would like to leave the textboxes empty when the value is null, everything is working fine for ShortDatString.

I need to figure out how to handle this like when value from DB is NULL:

s_ub_cen.Text = precti2.GetDecimal(59).ToString();

Thank you so much.

4

1 回答 1

3

You need to check for IsDBNull:

if(!precti2.IsDBNull(59))
{
    s_ub_cen.Text = precti2.GetDecimal(59).ToString();
}

Also, prevent SQL-Injection by using sql-parameters, don't concatenate strings to build the sql query.

Instead of:

SqlCommand command = new SqlCommand("SELECT * FROM zajezd WHERE akce='" + akce + "' and rocnik='" + klientClass.Rocnik() + "'", spojeni);

this:

using(var command = new SqlCommand("SELECT * FROM zajezd WHERE akce=@akce and rocnik=@rocnik", spojeni))
{
    command.Paramaters.AddWithValue("@akce", akce);
    command.Paramaters.AddWithValue("@rocnik", klientClass.Rocnik());
    // ....
}

Edit

is there any solution that would solve this for 20 textboxes ?

In general there is no automatism. You have to provide a sql-parameter for every dynamic input.

However, if you are looking for an elegant way to get a "safe-string" you could use this extension:

public static class DataExtensions
{
    public static string GetSafeString(this SqlDataReader reader, int colIndex)
    {
        if (!reader.IsDBNull(colIndex))
            return reader[colIndex].ToString();
        else
            return string.Empty;
    }
}

You use this method in this way:

_ub_cen.Text = reader.GetSafeString(59);
于 2013-08-26T07:30:07.473 回答