简体   繁体   English

使用阅读器检查字段是否包含空值

[英]using reader to check if a field contains null value

I am wanting to know how i can check if a field contains null value and replace it with text N/A or just not display the field. 我想知道如何检查字段是否包含空值并将其替换为文本N / A或不显示该字段。 But i don't want the code to break if the field contains null i want it to continue until all fields are filled with a value. 但是我不希望代码在字段包含null的情况下中断,我希望代码继续执行直到所有字段都填充一个值。

C# Code C#代码

using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT FirstName, LastName, Date FROM EOI WHERE (FormID = '13')";
        connection.Open();
        using (var reader = command.ExecuteReader())
        {
            while(reader.Read())
            {
                Label1.Text = reader["FirstName"].ToString();
                Label2.Text = reader["LastName"].ToString();
                DateTime Text = Convert.ToDateTime(reader["Date"]);
                Label3.Text = Text.ToString("d");
            }
        }
    }

You can either check this in C#: 您可以在C#中进行检查:

if(reader["FirstName"]==null)
{
 // Do something
}

or in T-SQL with ISNULL : 或在带有ISNULL的 T-SQL中:

SELECT ISNULL(FirstName,'N/A'), ISNULL(LastName,'N/A'), Date FROM EOI

I'm assuming that the null value you will have a problem with is the Date column. 我假设您遇到问题的空值是“ Date列。 A DateTime in C# cannot be null since it is a struct. C#中的DateTime不能为null,因为它是一个结构。 You would want to cast it to a nullable DateTime instead: 您可能希望将其强制转换为可空的DateTime:

DateTime? date = (DateTime?)reader["Date"];

Now it's up to you to perform logic when transforming this to a string: 现在由您决定将其转换为字符串时执行逻辑:

dateLabel.Text = date != null ? date.Value.ToString("d") : "N/A";

For the string columns just rewrite it as follows since strings are already nullable: 对于字符串列,只需按如下所示重写它,因为字符串已经可以为空:

firstNameLabel.Text = (string)reader["FirstName"] ?? "N/A";

You can either check in your select statement or in code. 您可以签入select语句或代码。 In SQL: 在SQL中:

SELECT IsNull(FirstName, 'N/A') as FirstName, 
        Coalesce(LastName, 'N/A') as LastName, Date FROM EOI WHERE (FormID = '13');

In .Net, you need to compare it to DbNull.Value: 在.Net中,您需要将其与DbNull.Value进行比较:

Label1.Text = reader["FirstName"] == DBNull.Value ? "N/A" :  Convert.ToString(reader["FirstName"]);

Note that in the above example, Convert.ToString() will convert nulls to empty strings. 请注意,在上面的示例中,Convert.ToString()会将空值转换为空字符串。 This is a third example of what you can do. 这是您可以做什么的第三个例子。

If you know the types in advance you can use (pseudo code as I'm typing on an iPhone): 如果您事先知道类型,则可以使用(我在iPhone上键入时的伪代码):

KnownType myData = reader.IsDbNull(fieldname) ? KnownType myData = reader.IsDbNull(fieldname)吗? MyDefaultValue : reader.GetKnownType(fieldname) MyDefaultValue:reader.GetKnownType(fieldname)

Eg String myData = reader.IsDbNull(fieldname) ? 例如,字符串myData = reader.IsDbNull(fieldname)吗? "" : reader.GetString(fieldname) “”:reader.GetString(fieldname)

String dateValue = reader.IsDbNull(fieldname) ? 字符串dateValue = reader.IsDbNull(fieldname)吗? "No date" : reader.GetDate(fieldname).ToString() “无日期”:reader.GetDate(fieldname).ToString()

This is more efficient and minimises casting. 这样更有效,并最大程度地减少了铸造。 For maximum efficiency you should also use the field index rather than the field name. 为了获得最大效率,您还应该使用字段索引而不是字段名称。 Every time you use the field name, the index has to be calculated: reader("Date") is reader.GetValue(reader.GetOrdinal("Date")) 每次使用字段名称时,都必须计算索引:reader(“ Date”)是reader.GetValue(reader.GetOrdinal(“ Date”))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM