use*_*873 5 .net sql sql-server asp.net dbnull
如果textBox字段为空,我想将SQL Server 2008数据库表中的所有行返回到SQL数据源.所以我用一个if @date IS NULL子句创建了一个存储过程.
虽然存储过程似乎在Visual Studio 2008中正常工作,但实际网页没有显示任何结果.
我猜我必须向DBNull存储过程发送一个值if if textBox.Text == string.Empty.我试过了,SqlDataSource1.SelectParameters.Add但似乎我得到转换错误DBNull.Value到字符串.
这是我的问题的根源还是我错过了其他的东西?DBNull.Value如果文本字段为空,我将如何传递到存储过程?
tpe*_*zek 10
您需要确保在SqlDataSource上将CancelSelectOnNullParameter设置为false,并且ConvertEmptyStringToNull对于所需参数为true.它应该在标记中看起来像这样:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" SelectCommand="...">
<SelectParameters>
<asp:ControlParameter Name="..." ControlID="..." PropertyName="..." DbType="..." ConvertEmptyStringToNull="true"/>
...
</SelectParameters>
</asp:SqlDataSource>
Run Code Online (Sandbox Code Playgroud)
如果您有多个可以提供空值的Control并且您只想允许其中一个为null,则问题将开始.在这种情况下,您必须将CancelSelectOnNullParameter设置为true并使用Selecting事件来添加DBNull.Value:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
if (String.IsNullOrEmpty(textBox.Text))
((IDbDataParameter)e.Command.Parameters["@name"]).Value = DBNull.Value;
}
Run Code Online (Sandbox Code Playgroud)
这应该可以让你解决你的问题.