如何默认所有 SqlDataSource 参数将空字符串转换为 null?

问题描述 投票:0回答:4

我有一个使用多个 FormView 和 SQLDataSource 的项目。我希望 SQLDataSource 的默认行为将空值插入为 null。我知道我可以通过为每个参数创建一个插入参数来做到这一点,但是对于必须执行此操作来更新并插入每个可能为空的参数来说,这真的很旧。

<InsertParameters>
    <asp:Parameter Name="Name" ConvertEmptyStringToNull="true" />
</InsertParameters>

web.config 或 SQLDataSource 中是否有我可以设置的设置?

c# sql-server sqldatasource formview
4个回答
1
投票

我总是从 Parameter 甚至 SqlDataSource 派生一个新类来更改我想要的默认行为。

public class MyDataSource : SqlDataSource
{        
    public MyDataSource()
    {
        if (HttpContext.Current != null)
        {
            this.ConnectionString = MyCinfig.ConnectionString;
            SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
            CancelSelectOnNullParameter = false;

            this.Updated += new SqlDataSourceStatusEventHandler(NXSDataSource_iudExecuted);
            this.Inserted += new SqlDataSourceStatusEventHandler(NXSDataSource_iudExecuted);
            this.Deleted += new SqlDataSourceStatusEventHandler(NXSDataSource_iudExecuted);
        }
    }
}

参数

public class UserIDParameter : Parameter
{
    public UserIDParameter()
    {
        this.Name = "user_id";
        this.DbType = System.Data.DbType.Int32;
    }

    protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control)
    {
        return GetMyCurrentUserID();
    }
}

0
投票

我这样做了:

foreach (Parameter p in sqlds.SelectParameters) {
    p.ConvertEmptyStringToNull = true;
}

0
投票
MyDataSource.CancelSelectOnNullParameter = False

这会将所有空字段转换为 null


-2
投票

覆盖“选择”事件并分配您需要的所有内容

© www.soinside.com 2019 - 2024. All rights reserved.