Link to home
Start Free TrialLog in
Avatar of ThanksWelcome
ThanksWelcomeFlag for Canada

asked on

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!
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

How are you populating the datagrid, can you post the relevant code?
Avatar of ThanksWelcome

ASKER

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

"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
SOLUTION
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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?
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!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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!!!
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" %>
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!
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!!!



Thanks!!!
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); %>