• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 309
  • Last Modified:

How to pass a c# variable to a sql datasource (asp c# sql server)

Hi, please see the code below.  I am trying to access a c# variable in a sqldatasource definition.  Could someone please tell me what I need to change to that I can use the domain variable in the WHERE?  Thanks!  I've been trying for hours...   (I am new to asp, c#  and sql server, since last 2 days).
I have the follwing code in a c# aspx file:
<%string domain = (HttpContext.Current.Request.ServerVariables["HTTP_HOST"]);%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:testfirststring %>" 
        SelectCommand="SELECT testField FROM table1test WHERE testField = '<% domain %>' "></asp:SqlDataSource>
I am missing something to have the domain variable to be accessible in the where statement.
Everything else works (for now)!  :)

Open in new window

  • 2
  • 2
1 Solution
just override OnPreRender and add the following :

protected override void OnPreRender(EventArgs e)
         this.SqlDataSource1.SelectCommand = String.Format("SELECT testField FROM table1test WHERE testField ='{0}'",HttpContext.Current.Request.ServerVariables["HTTP_HOST"]);
ThanksWelcomeAuthor Commented:
Hi, thanks for your help.

Unfortunately, being a newbie, I have absolutery no clue of how to override OnPreRender as you ask.

Also, I do not know where to add the code you provided.

Thanks for more details!

Just place it in the code behind, or even inside.

<script runat="server" type="text/C#">
Then dont set you SelectCommand on your SqlDataSource in the markup..
ThanksWelcomeAuthor Commented:
Woooohooo!!!  It works!  So happy, thank's!  (I'm do not understanding why, though, because I do not understand what do this function. Any extra thought? For example, what is the purpuse of the {0}? )  Thank's!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now