你好,我试着从Sql读取日期如下:
SqlCommand comm= new SqlCommand("SELECT * FROM zajezd WHERE akce='" + tentoradek + "' AND rocnik='" + rocnik + "'", spojeni);
spojeni.Open();
SqlDataReader read= comm.ExecuteReader();
if (read.Read())
{
object nulldate = (maskedTextBox2.Text = read.GetDateTime(24).ToShortDateString());
if (nulldate == null)
{
maskedTextBox2.Text = "__.__.____";
}
} 但是问题在于,当值为null时,我需要maskedTextBox为空。我总是得到这样的异常:“不能对空值调用此方法或属性”。
当特定列的值被读取为NULL时,如何避免maskedTextBox为空?
maskedTextBox上的掩码是00/00/0000
非常感谢你回答我的低质量问题。
发布于 2013-08-21 13:11:07
替换
object nulldate = (maskedTextBox2.Text = read.GetDateTime(24).ToShortDateString());使用
object nulldate = (maskedTextBox2.Text = read.IsDBNull(24) ? string.Empty : read.GetDateTime(24).ToShortDateString()); 发布于 2013-08-21 13:00:08
我不知道什么是SqlDataReader,但我认为这应该是,对吧?
然而。您的读者有一个名为IsDbNull(INDEX)的方法,您可以在这里检查特定列是否为DbNull。
只是为了获得信息:您不应该像这样构建SQL-查询:
SqlCommand comm= new SqlCommand("SELECT * FROM zajezd WHERE akce='" + tentoradek + "' AND rocnik='" + rocnik + "'", spojeni);相反,请尝试以下代码:
SqlCommand command = new SqlCommand("SELECT * FROM zajezd WHERE akce=@akce and rocnik=@rocnik", spojeni);
command.Parameters.AddWithValue("@akce", tentoradek);
command.Parameters.AddWithValue("@rocnik", rocnik);https://stackoverflow.com/questions/18357939
复制相似问题