-2

I have my two select statements (Str1,Str2) in two string variables. I also have a condition where the appropriate select statement is selected and assigned to another string (res).

This is the select statement that is to be assigned to the SelectCommand property of a SqlDataSource control on my web page.

The code is:

int id =1;
string Str1 = "Select * from table";
string Str2 = "Select * from table where id = "+id;
string res;
if(id == 0)
{
  res=Str2;
}else
{
  res=Str1;
}

My markup looks like:

<asp:gridview.....></aspgridview>
<asp:SqlDataSource ID="ds1" runat="server"
  ConnectionStrings="<%ConnectionStrings.ConnStr%>"
  SelectCommand="<%# res%>">
</asp:SqlDataSource>

How do I assign my string variable res to my SqlDataSource SelectCommand attribute from my codebehind or inline C# code?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
gnome123
  • 35
  • 2
  • 10

3 Answers3

3

You cann set the SelectCommand property from your code-behind, by adding the following statement after the if/else block:

ds1.SelectCommand = res;

Then you can remove the expression from the markup code:

<asp:SqlDataSource ID="ds1" runat="server"
  ConnectionStrings="<%ConnectionStrings.ConnStr%>" />
M4N
  • 94,805
  • 45
  • 217
  • 260
1

You should be using it like in Using Parameters with the SqlDataSource Control aricle on msnd.

If you just append strings like that you're going to have an SQL Injection vulnerability.

neeKo
  • 4,280
  • 23
  • 31
0

To programatically assign your SelectCommand for your SqlDataSource:

ds1.SelectCommand = res;

Where res is your command text.

Brissles
  • 3,833
  • 23
  • 31