如何将asp.net c#中的null值传递给sql查询?

时间:2016-05-05 07:03:50

标签: c# asp.net

我有一个下拉列表,其中数据动态绑定。让我来探索吧。 我使用了五个下拉列表,如果选择了索引0,我必须要传递空值。  我试过这样但返回空字符串。

 drp_sub_stream.Items.Insert(0, new ListItem("Select a Sub Stream", null));
 drp_sub_stream.Items.Insert(0, new ListItem("Select a Sub Stream", DBNull.Value.ToString()));

然后我尝试了这个

drp_sub_stream.Items.Insert(0, new ListItem("Select a Sub Stream", "NULL"));

但它以字符串形式返回null。我在按钮点击时从我搜索数据的位置传递此值。 按钮单击代码:

 public void _SearchCollege(string _CountryName,string _University, string _LevelName, string _Interest,string _Substream)
    {

        using (SqlConnection con = new SqlConnection(CS))
        {

            con.Open();

            //string s = "select * from edu_college_desc where (country= @country and university=@university and leveln= @level and interest= @interest and substream=@substream) or (country=@country or university=@university or leveln=@level or interest=@interest or substream=@substream) ";

            string s= "select * from edu_college_desc where country = ISNULL(@country ,country) and university = ISNULL(@university ,university)   and leveln      =   ISNULL(@level ,leveln) and interest    =   ISNULL(@interest ,interest) and substream   =   ISNULL(@substream,substream)";
            SqlDataAdapter da = new SqlDataAdapter(s, con);
            da.SelectCommand.Parameters.AddWithValue("@country", _CountryName);
            da.SelectCommand.Parameters.AddWithValue("@university", _University);
            da.SelectCommand.Parameters.AddWithValue("@level",_LevelName);
            da.SelectCommand.Parameters.AddWithValue("@interest", _Interest);
            da.SelectCommand.Parameters.AddWithValue("@substream", _Substream);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                HttpContext.Current.Session["edusearch"] = dt;
                HttpContext.Current.Response.Redirect("edusearch.aspx");

            }
            else
            {
                HttpContext.Current.Session["edusearch"] = null;
                HttpContext.Current.Response.Redirect("edusearch.aspx");
            }
        }
    }

需要解决方案。

1 个答案:

答案 0 :(得分:0)

drp_sub_stream.Items.Insert(0, new ListItem("Select a Sub Stream", "0"));

drp_sub_stream.Items.Insert(0, new ListItem("Select a Sub Stream", String.Empty));

然后你可以使用一个简单的如果SelectedValue等于零或string.Empty并决定是否应用和过滤(在sql查询中连接)

string s= "select * from edu_college_desc where country = ISNULL(@country ,country) and university = ISNULL(@university ,university)   and leveln      =   ISNULL(@level ,leveln) and interest    =   ISNULL(@interest ,interest)";
if(!String.IsNullOrEmpty(_SubStream))
    s+= " and substream   =   ISNULL(@substream,substream)";
...


if(!String.IsNullOrEmpty(_Substream)) 
   da.SelectCommand.Parameters.AddWithValue("@substream", _Substream);

通过这种方式,您还可以使用必需的验证器来检查您是否选择了一个值(在零例中,您必须添加InitialValue="0"