简体   繁体   中英

Common parameters for SQLDATASOURCE in asp.net c#

The Insert and Update parameters are SAME for my Sqldatasource.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>" 
             <InsertParameters>
                    <asp:Parameter Name="id" Type="Int32" />
                    <asp:Parameter Name="startdt" Type="DateTime" />
                    <asp:Parameter Name="enddt" Type="DateTime" />
                    <asp:Parameter Name="title" Type="String" />
                    <asp:Parameter Name="detail" Type="String" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="id" Type="Int32" />
                    <asp:Parameter Name="startdt" Type="DateTime" />
                    <asp:Parameter Name="enddt" Type="DateTime" />
                    <asp:Parameter Name="title" Type="String" />
                    <asp:Parameter Name="detail" Type="String" />                    
                </UpdateParameters>

In code behind I have to write depending on Insert or Update:

SqlDataSource1.InsertParameters["Title"].DefaultValue = "Title"

SqlDataSource1.UpdateParameters["Title"].DefaultValue = "Title" 

There is lot of same stuff that gets repeated. I was wondering if there is a way to eliminate the same repetitive lines in aspx (same parameters) and in code behind. This would be huge time saver and also help reduce errors.

Both InsertParameters and UpdateParameters are parameters of the ParameterCollection class.

So you could have a helper function that will set all the common parameters. Based on the code snippet in your question, the helper function can be:

using System.Web.UI.WebControls;

public void SetCommonParameters(ParameterCollection params)
{
    params["Title"].DefaultValue = "Title";
    // add all common parameters
}

When you do an insert you call:

SetCommonParameters(SqlDataSource1.InsertParameters);

When you do an update you call:

SetCommonParameters(SqlDataSource1.UpdateParameters);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM