Click here to Skip to main content
15,895,256 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys ,
I'm trying to retrive some values from two different tables(SQL) but I get generall exception error.

What I mean is I have table sales and table item_sales

with the following code I retrive the correct values from variables that i need
C#
protected string InputId { get; set; }
    protected string InputValue { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        //this.InputValue = "100";
        SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        SqlCommand sqlCommand = new SqlCommand("select id_product,price from item_sales where id_sales=(select max(id_sales) from item_sales)", con1);
        con1.Open();

        using (SqlDataReader read = sqlCommand.ExecuteReader())
        {
            while (read.Read())
            {
                string id_product = read["Id_product"].ToString();
                string price = read["price"].ToString();
              //  this.InputValue = price;
                this.InputId = id_product;
            }
            read.Close();
        }
        con1.Close();


But I need in the same page if that is possible to retrieve the full price item so i add the following code
C#
SqlCommand sqlCommand2 = new SqlCommand("select price_item from sales where id_sales=(select max(id_sales) from sales)", con1);
        con1.Open();
        using (SqlDataReader read2 = sqlCommand.ExecuteReader())
        {
            while (read2.Read())
            {


                string total_cart_price = read2["price_item"].ToString();
                this.InputValue = total_cart_price;

            }
            read2.Close();
        }
        con1.Close();


but i receive an error "IndexOutOfRangeException was unhandled by user code"

Is any way to retrieve values from two different tables? and how?

Thnx in advance for yours Time!

Jason!
Posted
Updated 14-Oct-13 1:33am
v2

Your return query may not have any records to read. I would change your code to check to make sure that the reader has rows

C#
if (read2.HasRows == true)
{
 while(read2.Read())
 {
  //do sutff
 }
}


further reading Retrieving Data Using a DataReader[^]
 
Share this answer
 
v2
it worked!!! thank you for your help my friend
except for that i found another error that i have in my code:

here-> using (SqlDataReader read2 = sqlCommand.ExecuteReader())
i shoud be have :-> using (SqlDataReader read2 = sqlCommand2.ExecuteReader())
because i was making the query at the wrong table!

Thnx for your help and your time
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900