0
public partial class FrmOnline : System.Web.UI.Page
{
    string Query;
    SqlCommand cmd;
    SqlConnection conn;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
                     OpenSQLConnection();
           SqlCommand cmd = new SqlCommand("select * from Info1 where UID=1", conn);
           SqlDataReader dr;
           dr = cmd.ExecuteReader();
           while (dr.Read())
           {
               dr.Read();
               TextBox1.Text = dr[0].ToString();
           }
            
        }
    }


 private void OpenSQLConnection()
    {
        try
        {

            conn = new SqlConnection("Data Source=(local);Initial catalog=sonia;User ID=sonia;Password=sonia;");
            conn.Open();

        }
        catch (Exception ex)
        {
            
        }

    }

I m getting error in line TextBox1.Text = dr[0].ToString();
Invalid attempt to read when no data is present.

But the record is there in DB,of UID 1.then y the error is coming.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by shenulal
0
public partial class FrmOnline : System.Web.UI.Page
{
    string Query;
    SqlCommand cmd;
    SqlConnection conn;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
                     OpenSQLConnection();
           SqlCommand cmd = new SqlCommand("select * from Info1 where UID=1", conn);
           SqlDataReader dr;
           dr = cmd.ExecuteReader();
           while (dr.Read())
           {
               dr.Read();
               TextBox1.Text = dr[0].ToString();
           }
            
        }
    }


 private void OpenSQLConnection()
    {
        try
        {

            conn = new SqlConnection("Data Source=(local);Initial catalog=sonia;User ID=sonia;Password=sonia;");
            conn.Open();

        }
        catch (Exception ex)
        {
            
        }

    }

I m getting error in line TextBox1.Text = dr[0].ToString();
Invalid attempt to read when no data is present.

But the record is there in DB,of UID 1.then y the error is coming.

hai,
Rewrite the code like this and try again

if (!IsPostBack)
{
OpenSQLConnection();
SqlCommand cmd = new SqlCommand("select * from Info1 where UID=1", conn);

SqlDataReader dr;
try
{
    dr = cmd.ExecuteReader();
if(dr.HasRows)
{
dr.Read();
TextBox1.Text = dr[0].ToString();
}
}
}
catch(Exception){}
finally
{
if(dr!=null) dr.Close();
}
}
}

update me with the result.

Thanks,
Shenu

Edited by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.