【问题标题】:convert.isBDnull("foo") strange behaviorconvert.isDBnull("for") 奇怪的行为
【发布时间】:2014-01-11 16:59:00
【问题描述】:

我有给定的代码:

文件.ascx.cs

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource.SelectCommand = @"SELECT reu.duree_minutes as DUREE
                                            FROM z_reunions reu"
    List.DataSourceID = "SqlDataSource";
    List.DataBind();
}

文件.ascx

<asp:SqlDataSource ID="SqlDataSource" runat="server"></asp:SqlDataSource>
<asp:ListView ID="List" runat="server">

    ...
    <%if (Convert.IsDBNull("DUREE"))
      { %>
         <asp:Label ID="Label6" runat="server" Text='NULL' ></asp:Label>
    <%} else { %>
         <asp:Label ID="Label8" runat="server" Text='<%# Eval("DUREE").GetType() %>'></asp:Label>
    <%} %>

我得到了以下输出:

System.DBNull
System.DBNull
System.DBNull
System.DBNull
System.Int32
System.Int32

但我希望它是:

NULL
NULL
NULL
NULL
System.Int32
System.Int32

我错了吗?还是有什么奇怪的行为?

【问题讨论】:

  • 字符串"DUREE" 永远不会等于DBNull。你的意思是if (Convert.IsDBNull(Eval("DUREE"))
  • 您正在检查字符串类型的对象是DBNull,这是错误的。
  • @Samoth 再次阅读了我的评论。你永远不会在if,总是在else
  • 因为 Eval("DUREE") 为你所说的 Eval 返回行的“DUREE”列的值
  • @CodeCaster 你编辑了它;)我测试过,它抛出这个System.InvalidOperationException

标签: c# dbnull


【解决方案1】:

试试这个

<%# Eval("DUREE") == DBNull.Value ? <%# Eval("DUREE").GetType().ToString() %> : "NULL" %>

或者只是

<%# Eval("DUREE") == DBNull.Value ? "System.DBNull" : "NULL" %>

使用 和 "NULL" 你可以添加 html

请参阅此处以了解在 if 语句中使用 Eval eval in if statement?

您可以将代码与 2 个标签一起使用,并将 Visible 属性与 Eval 一起使用

<asp:SqlDataSource ID="SqlDataSource" runat="server"></asp:SqlDataSource>
<asp:ListView ID="List" runat="server">

    ...
    <asp:Label ID="Label6" runat="server" Text='NULL' Visible='<%# Eval("DUREE") == DBNull.Value %>'></asp:Label>
    <asp:Label ID="Label8" runat="server" Text='<%# Eval("DUREE").GetType() %>' Visible='<%# Eval("DUREE") != DBNull.Value %>'></asp:Label>

【讨论】:

  • 你的第二个解决方案有效,但这导致我this问题
猜你喜欢
  • 2011-07-28
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多