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?
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%>" />