如何检查查询字符串是否为空

时间:2015-03-30 13:29:30

标签: c# sql sql-server

我使用C#查询表并生成以下SQL行:

'det.aspx?ObjectID=' + CAST(CT.OBJECTID AS VARCHAR) + '&cid=45&fid=' + ISNULL(CAST(CT.A0900 AS VARCHAR), '') 'TD'

产生

http://localhost:3652/Pages/det.aspx?ObjectID=1092648&cid=45&fid=

我试图获取fid的值,如果它不为空或者是否有值:

if (Request.QueryString["fid"] != null || Request.QueryString["fid"].Length > 0)
{
    string t = Request.QueryString["fid"];
}

使用上面的示例,它不应该输入if caluse,但它是。

我该如何解决呢?

2 个答案:

答案 0 :(得分:2)

将您的查询更改为:(在其中使用case语句)

'det.aspx?ObjectID=' + CAST(CT.OBJECTID AS VARCHAR) + '&cid=45'+

case when CT.A0900 is not null then '&fid='+CAST(CT.A0900 AS VARCHAR)
else '' end

答案 1 :(得分:1)

检查null或空字符串时,请使用string.IsNullOrEmptystring.IsNullOrWhiteSpace的内置.NET字符串方法:

if ( !string.IsNullOrWhiteSpace(Request.QueryString["fid"]) )
{
    string t = Request.QueryString["fid"];
}

当字符串由于or语句而为空时,此条件将成功。请注意,empty与null不同:

if (Request.QueryString["fid"] != null || Request.QueryString["fid"].Length > 0)
{
    // "fid" could be empty, not null which causes the first condition to succeed.
    string t = Request.QueryString["fid"];
}

您想要使用&&上面的陈述:

if (Request.QueryString["fid"] != null && Request.QueryString["fid"].Trim().Length > 0)
{
    string t = Request.QueryString["fid"];
}
相关问题