Asp c# sql server: How to pass the result of the first sql field to a c# variable?

I have an aspx page, in c#, with a working sql request.  The sql request returns just 1 row everytime, with just one field, testField.

I can see the correct result in a datagrid.  But, how to pass this to a c# variable?

Thanks!
ThanksWelcomeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
How are you populating the datagrid, can you post the relevant code?
0
ThanksWelcomeAuthor Commented:
Thanks for your answer.  Yes, I post it below, but please note the data grid is somehow irrelevant to the final result, as I use it just for testing, to make sure all the sql request work.  So it will ultimately be removed.  

The name of the datasource is SqlDataSource1, while the name of the field is testField.  Only one row is expected as a result everytime.  I do not need to implement verification at this point.  Thanks!
    <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
        EnableModelValidation="True" AutoGenerateColumns="False" 
        BorderStyle="None" style="text-align: center" Width="267px">
        <Columns>
            <asp:BoundField DataField="testField" HeaderText="testField" SortExpression="testField" />
         
        </Columns>
    </asp:GridView>

Open in new window

0
guru_samiCommented:
"but please note the data grid is somehow irrelevant to the final result, as I use it just for testing, to make sure all the sql request work.  So it will ultimately be removed. "

In that case can you let us know what exactly would be the real scenario.
As the code will vary depending on if you are using GridView, sqlDatasource or none of those.

Or do you mean you want to execute a SQL query and retrieve the results in code-behind?
Then you can look into using SqlDataReader like below:

// 1. Instantiate the connection
        SqlConnection conn = new SqlConnection(YourconnectionString);
        SqlDataReader rdr = null;
        try
        {
            // 2. Open the connection
            conn.Open();
            // 3. Pass the connection to a command object
            SqlCommand cmd = new SqlCommand(yourQuery,conn);
            //
            // 4. Use the connection
            //
            // get query results
            rdr = cmd.ExecuteReader();
            // print the CustomerID of each record
            while (rdr.Read())
            {
                string result = rdr["testField"].ToString();
            }
        }
        finally
        {
            // close the reader
            if (rdr != null)
            {
                rdr.Close();
            }

            // 5. Close the connection
            if (conn != null)
            {
                conn.Close();
            }
        }

Code Reference:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx
0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

Snarf0001Commented:
For the most part agree with guru_sami, if you're not actually binding to a grid and just want it in a variable, then do the query in code-behind, not in the aspx.

Only thing I would suggest is using cmd.ExecuteScalar() instead of .ExecuteReader().
If your only getting one value back each time, that's what Scalar is inteded to do, return the first column of the first row of the first result set.

ie:

string myVariable = cmd.ExecuteScalar().ToString();
0
ThanksWelcomeAuthor Commented:
Hi!  I am sorry if context was not clear.

I think the best would be to take a look at my attached whole page below.  For the moment, if I could just be able to pass the  field "Domain" (this is the real name for the testField in the real page attached), for the first row, to a c# variable from the connection sqldatasource1 , It'd be fantastic.  :)

Important note1:  please take note, on begining of document, of:  protected override void OnPreRender(EventArgs e)...
Important note2:  Configured this way, I already obtain successufully the row I need.  I just need to pass the result to a variable.

Thank's!   (And I'm sorry if this question has been kind of messy in the description...)
defaultpage.txt
0
guru_samiCommented:

Good Point. Thanks.

Just a small question:
So Ideally you don't need this code right?
----Following code is just for test right ....and not required----
 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
        EnableModelValidation="True" AutoGenerateColumns="False"
        BorderStyle="None" style="text-align: center" Width="267px">
        <Columns>
            <asp:BoundField DataField="Domain" HeaderText="Domain" SortExpression="Domain" />
         
        </Columns>
    </asp:GridView>
   
    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
     <%# Eval("Domain")%>
</ItemTemplate>
</asp:Repeater>
------End of Test Code----------

If so then what exactly are you trying to accomplish?
0
ThanksWelcomeAuthor Commented:
Right.  In fact this code is for testing purposes.  It helped me to realize visually that I really get the result I want from the database.  It almost fills the need I describe, but it prints the result in the web page instead of puting it in a variable.  I really hope I am clear, you are very patient...  thanks!
0
guru_samiCommented:
Ok then you do not need even SqlDataSource and that OnPreRender method as well....
Try something like below:
 protected void Page_Load(object sender, EventArgs e)
    {
 // assuming there is a connectionsting with name "testfirststring" in your web.config.
        string connectionString = ConfigurationManager.ConnectionStrings["testfirststring"].ConnectionString;

// 1. Instantiate the connection
        SqlConnection conn = new SqlConnection(connectionString);
          try
        {
            // 2. Open the connection
            conn.Open();
            // 3. Pass the connection to a command object
// This is the query taken from the code you provided
           string query = String.Format("SELECT Domain FROM table1test WHERE Domain ='{0}'",HttpContext.Current.Request.ServerVariables["HTTP_HOST"]);

            SqlCommand cmd = new SqlCommand(query,conn);
           // get query results
           //Thanks to Snarf0001:
                   string myVariable = cmd.ExecuteScalar().ToString();
              }
        finally
        {          
            // 5. Close the connection
            if (conn != null)
            {
                conn.Close();
            }
        }
}

Note: Instead of putting this function in .aspx file you can move it to your code behind file i.e. .aspx.cs
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ThanksWelcomeAuthor Commented:
Hi!  This looks just fantastif, I'm sure it will work!  One problem though:  SqlCommand and SqlConnection generate an error:  The type or namespace name  could not be found, are you missing a using or assembly refenrence?

I tried to add  :
using System.Data;
using System.Data.SqlClient;

But it did not change.  I'm sure we are done after this!  :)  Thanks!!!
0
guru_samiCommented:
Where did you add System.Data.SqlClient;?
in your code behind or in .aspx page itself?
if its on .aspx page you should add this at the top of the page after you <@Page..> directive:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
0
ThanksWelcomeAuthor Commented:
Hi!  Import worked the way you gave it... Oh oh:  when I compile, I get this message:  On line:   string myVariable = cmd.ExecuteScalar().ToString();  

System.NullReferenceException

I'm so sorry, can we give 5000 points?  THanks!
0
ThanksWelcomeAuthor Commented:
No problem finally with the null exception:  it is because I did not have result to my query:  I was not online.  Now it works.

Thanks for everything!  

Next step:  I do not know how to access the variable:  it seems the scope is not outside the function?  I tried to do a:

<% Response.Write(myVariable); %>  , from the body, and it did not work because this variable did not exist in the context.  Nice if you had a clue, but, well, thank you very much for your great great help!!!



0
ThanksWelcomeAuthor Commented:
Thanks!!!
0
guru_samiCommented:
you can declare a public variable like below:
public string myVariable;
 protected void Page_Load(object sender, EventArgs e)
    { //rest of your code...with minor chage
                myVariable = cmd.ExecuteScalar().ToString();
}
Then you can access it as:
<% Response.Write(this.myVariable); %>
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.