[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 280
  • Last Modified:

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!
0
ThanksWelcome
Asked:
ThanksWelcome
2 Solutions
 
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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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
 
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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