Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Code in GridView

Tags:

c#

.net

asp.net

I'm converting a classic ASP site to ASP.NET (C#) and there are several stored procedures that can be called from one page. Currently in the classic ASP the values such as the stored procedure name and other parameters are passed in the query string. I'm trying to determine a way of doing this in ASP.NET now as I cannot seem to use variables as the stored procedure name. What I tried to do was the following:

<% string sp = Request.QueryString["sp"]; %>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
    SelectCommand="<%= sp%>" SelectCommandType="StoredProcedure">

The second part of this is that of the stored procedures, there can be a different number of parameters needed. In my classic ASP I was passing the parameters over via query string but first checking to see if they were blank and if so, not to attempt to pass them as a parameter to the stored procedure. Here is how I was doing it in classic ASP:

If param1 <> "" then
    cmd.Parameters(i) = param1
    i=i+1
End If
If param2 <> "" then
    cmd.Parameters(i) = param2
    i=i+1
End If
    If param3 <> "" then
    cmd.Parameters(i) = param3
    i=i+1
End If
If param4 <> "" then
    cmd.Parameters(i) = param4
End If

I don't see a way to accomplish this in .NET either since I can't place code within the GridView. How can do accomplish both of these pieces?

Edit: I've solved the first half of my problem by doing the following in my Page_Load event as follows:

protected void Page_Load(object sender, EventArgs e)
{
    sp = Request.QueryString["sp"];
    SqlDataSource1.SelectCommand = sp;
}

Now the only remaining issue is how to only pass parameters with values assigned.

like image 768
aantiix Avatar asked Jul 22 '26 11:07

aantiix


1 Answers

Problem solved. In the code behind:

protected void Page_Load(object sender, EventArgs e)
{
    sp = Request.QueryString["sp"];
    param1 = Request.QueryString["param1"];
    param2 = Request.QueryString["param2"];
    param3 = Request.QueryString["param3"];

    SqlDataSource1.SelectCommand = sp;

    if (param1 != null)
    {
        SqlDataSource1.SelectParameters.Add("param1", param1);
    }
    if (param2 != null)
    {
        SqlDataSource1.SelectParameters.Add("param2", param2);
    }
    if (param3 != null)
    {
        SqlDataSource1.SelectParameters.Add("param3", param3);
    }
}

In the aspx

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
    SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
like image 63
aantiix Avatar answered Jul 25 '26 02:07

aantiix