Monday, February 20, 2012

Problem with datareader

Hello

i creae one programm, there is an two data reader and two Gridview or datagrid , and my programm have one error

my programm is there

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class aries : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataReader dr1;
SqlCommand cmd1;

protected void Page_Load(object sender, EventArgs e)
{
string str;
str = ConfigurationSettings.AppSettings["DBconnect"];
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("select color from zodiac_color where Sno=1", con);
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
cmd1=new SqlCommand("select number from zodiac_number where Sno=1",con);
dr1 = cmd.ExecuteReader();
GridView2.DataSource = dr1;
GridView2.DataBind();

}
}

i want to calll two value in a same database but the table is diffrent

so please help me ?

The error is ::---

There is already an open DataReader associated with this Command which must be closed first.

please help me

ashwani kumar

dr.Close();
cmd1=new SqlCommand("select number from zodiac_number where Sno=1",con);
dr1 = cmd1.ExecuteReader();

Basically you are trying to use the same connection and command to open 2 datareaders. DataReaders make exclusive use of connections until you actually close them.

However, you don't need a datareader to obtain sinlge values. You should use ExecuteScalar for that. On the other hand, you should be able to use a JOIN in your query to link both tables and return both values at once in one datareader.

|||

You can addMultipleActiveResultSets=True inside your ConnectionString in web.config file and use this code:

SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["DBconnect"]);
SqlCommand command = conn.CreateCommand();
command.CommandText = "select color from zodiac_color where Sno=1";
SqlCommand command2 = conn.CreateCommand();
command2.CommandText = "select number from zodiac_number where Sno=1";
conn.Open();
GridView1.DataSource = command.ExecuteReader();
GridView2.DataSource = command2.ExecuteReader();
GridView1.DataBind();
GridView2.DataBind();
conn.Close();

No comments:

Post a Comment