Using column name when using SqlDataReader.IsDBNull
You are looking for SqlDataReader.GetOrdinal
According to MSDN
Gets the column ordinal, given the name of the column.
if (read.Read())
{
int colIndex = read.GetOrdinal("MyColumnName");
maskedTextBox2.Text = read.IsDBNull(colIndex) ?
string.Empty :
read.GetDateTime(colIndex).ToString("MM/dd/yyyy");
}
As a side note, your query is open to sql injection. Do not use a string concatenation to build a sql command but use a parameterized query
string query = "SELECT * FROM zajezd WHERE event=@p1 AND year=@p2";
using(SqlCommand cmd= new SqlCommand(query, spojeni))
{
spojeni.Open();
cmd.Parameters.AddWithValue("@p1",thisrow);
cmd.Parameters.AddWithValue("@p2",klientClass.Year().ToString());
using(SqlDataReader read= cmd.ExecuteReader())
{
......
}
}
I would try (string)(reader["ColumnName"] == DBNull.Value ? "" : reader["ColumnName"]);
to do it by the column name.
You could use GetOrdinal
to create your own IsDBNull(string name)
extension method.
[DebuggerStepThrough]
public static class SqlDataReaderExtensions
{
/// <summary>Gets a value that indicates whether the column contains non-existent or missing values.</summary>
/// <param name="name">The name of the column. </param>
/// <returns> <see langword="true" /> if the specified column value is equivalent to <see cref="T:System.DBNull" />; otherwise <see langword="false" />.</returns>
/// <exception cref="T:System.IndexOutOfRangeException">The name specified is not a valid column name. </exception>
public static bool IsDBNull(this SqlDataReader reader, string name)
{
int columnOrdinal = reader.GetOrdinal(name);
return reader.IsDBNull(columnOrdinal);
}
}
// Usage
if (read.Read())
{
maskedTextBox2.Text = read.IsDBNull("MyColumnName") ?
string.Empty :
read.GetDateTime("MyColumnName").ToString("MM/dd/yyyy");
}