Search code examples
c#asp.netsqldatasourcestring-concatenation

string expression for html tag value


I'm defining a datasource (for a sortable listview) and have a minor snag.

Code analogous to this works:

<asp:SqlDataSource ID="myDataSource" runat="server"
  SelectCommand="SELECT [aField], [bField]  FROM Suggestions WHERE stype = 'X'"
  ConnectionString="<%$ ConnectionStrings:dbConnectionString %>" >
</asp:SqlDataSource>

But the real select string is much more complicated, I want to do something like this:

<asp:SqlDataSource ID="myDataSource" runat="server"
  SelectCommand="SELECT [aField], [bField]  " +
                     "FROM Suggestions WHERE stype = 'X'"
  ConnectionString="<%$ ConnectionStrings:dbConnectionString %>" >
</asp:SqlDataSource>

I've searched on different variations of the terms: concatentation catenation string tag html asp.net

but I can't find anything about it, although it looks like it requires a string literal and not a string expression. So I'm eventually going to define this entire complicated function as a function in the database, but for now I would like to try something like:

<asp:SqlDataSource ID="myDataSource" runat="server"
  SelectCommand="<% qry_str('X'); %>"
  ConnectionString="<%$ ConnectionStrings:dbConnectionString %>" >
</asp:SqlDataSource>

where qry_str() is defined in code behind; however, that particular code does not work:

Code behind is defined as:

protected string qry_str(string t)
{
    string s =
    "SELECT [aField], [bField]  " +
             "FROM Suggestions WHERE stype = '" + t + "'";
    return "s";
}

I do not think the code behind is the problem. I think it's the asp.net and or the way I'm calling it. What is the right way to do what I'm trying to do?


Solution

  • You can set this attribute in some page event handler (whichever fits your workflow better). For example, in the Page_Load:

    protected void Page_Load(object sender, EventArgs e)
    {
        string t = "X"; // calculate t here
        myDataSource.SelectCommand = "SELECT [aField], [bField] FROM Suggestions WHERE stype = " + t;
        // other actions
    }