数据库
首页 > 数据库> > c# – 在WebForm中的SqlDataSource中跳过sql参数的设置值

c# – 在WebForm中的SqlDataSource中跳过sql参数的设置值

作者:互联网

我在asp.net中创建一个WebForm,我想用asp:SqlDataSource中的数据显示gridview
当我尝试跳过某些参数的值(传递null)时,我的问题就出现了.

这是我的代码的一些片段

在aspx文件中sqldatasource看起来像

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ConnectionStrings:ApplicationServices %>" 
        SelectCommand="art_bat_art" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:Parameter Name="art_naz" DefaultValue="HLA"  ConvertEmptyStringToNull="true" Type="String" />
            <asp:Parameter Name="art_sifra"     DbType="String"  Direction="Input"/>
            <asp:Parameter Name="vrsta_id" DefaultValue="3"   ConvertEmptyStringToNull="true" Type="Int32" />     
            <asp:Parameter Name="podvrsta_id" DefaultValue="13"   ConvertEmptyStringToNull="true" 
                Type="Int32"  />
            <asp:Parameter Name="podgrupa2"  DefaultValue="1365"   ConvertEmptyStringToNull="true" Type="Int32"      /> 
            <asp:Parameter Name="podosobine"   DefaultValue="1:9241"  ConvertEmptyStringToNull="true" 
                Type="String"  />
            <asp:Parameter Name="podosobineOR" DefaultValue="true"   ConvertEmptyStringToNull="true" 
                Type="Boolean"  />
        </SelectParameters>

我的网格看起来像这样:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="id" DataSourceID="SqlDataSource1">

代码背后还有麻烦
我的存储过程的参数之一是可选的,如果我在SQL中将它作为null传递给存储过程
无论如何要执行.

我试图跳过并传递该参数如下

public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }
        protected void Button1_Click1(object sender, EventArgs e)
        {
            SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = DBNull.Value; //Cannot implicitly convert type 
            SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = System.Data.SqlTypes.SqlString.Null;   //Cannot implicitly convert type 
            SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = System.Data.SqlTypes.SqlString.Null.ToString();   //IT compiles but i get NULL as text in SQL
            //IF I Just skip seting of this parametar, My SqlDataSource won't call stored proce 
            SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = string.Empty; //Again no execution of stored proce
            //Even if I call SqlDataSource1.DataBind(); //nothing cames to sql 
            GridView1.DataBind();
        }
    }

解决方法:

您必须编辑SQL(或存储过程)才能处理可选参数.

即:如果你有:

SELECT youh FROM yourTable WHERE art_sifra = @art_sifra

将其更改为:
从youTable WHERE中选择blah(art_sifra = @art_sifra或@art_sifra =”)

然后只需更改ConvertEmptyStringToNull =“false”并将select参数设置为“”:
SqlDataSource1.SelectParameters [“art_sifra”].DefaultValue =“”;

还需要在数据源上设置CancelSelectOnNullParameter =“false”.

标签:c,asp-net,gridview,sqldatasource
来源: https://codeday.me/bug/20190614/1237689.html