Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
  try
            {
                SqlConnection con = new SqlConnection(" Data Source=AHSAN-PC\\SQLEXPRESS;Initial Catalog=bank;Integrated Security=SSPI;MultipleActiveResultSets=True;");
                con.Open();
                //MessageBox.Show("connected");
                SqlCommand cmd = new SqlCommand("select * from account",con);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read().Equals(textBox1.Text))
                {
                    MessageBox.Show("sorry duplicate acc no.");
                }
                else
                {
                    //SqlCommand cmd = new SqlCommand("select * from account",con);
                    cmd=new SqlCommand("insert into account values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')", con);
                    SqlDataReader drr = cmd.ExecuteReader();
                    drr.Close();
                    MessageBox.Show("data added");
                    
                    
                }
                dr.Close();
                con.Close();
                //MessageBox.Show("data added");
            }
            catch (Exception ex)
            {
                MessageBox.Show("error" + ex.Message);
}
I am getting error of "There is an already open Datareader associated with this command that must be closed first."

Kindly help me. I am using sql server 2005 and C#.

I am giving 2 sql queries in code one of select and other of insert.as i want to prevent duplication in account No. records in my application.
Posted
Updated 14-Aug-11 23:36pm
v3
Comments
Abhinav S 15-Aug-11 5:22am    
Pre tags removed from question.

Just the error message is not sufficient to debug the issue.

If you are using nested Datareaders, you will need to enable Multiple Active Record Sets.
The database should support this as well. Here is an example[^].

MARS is generally activated via the connection string[^].
 
Share this answer
 
v2
You cant use the SqlDataReader for a second request while the first request is not jet finished (Close() command). Better have a second SqlDataReader object for the second query.
 
Share this answer
 
You use opened datareader and execute command at the same time.
In this case you could replace following block of code:
SqlCommand cmd = new SqlCommand("select * from account",con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read().Equals(textBox1.Text))

With something like this:
var cmd = new SqlCommand("SELECT COUNT (*) FROM [account] WHERE fieldname = @fieldname",con);
cmd.Parameters.AddWithValue("@fieldname", textBox1.Text);
var isExists = Convert.ToInt32(cmd.ExecuteScalar()) > 0;
if (isExists)

This will solve problem, just replace "fieldname" with name of field in db table to which you compare textBox1.Text.

Some small recommendations:
1. Do not use non-prepared strings in your sql queries (problem of sql-injection). Use parameters instead;
2. Store connection string in application configuration file in <connectionstrings> section;
3. Provide more attention to disposable resources. In case of any problem in try block db connection will stay open;
4. Use string.Format or StringBuilder for string concatenation;
If it's just test project or example then never mind :)
 
Share this answer
 
v3
Comments
duaa2 15-Aug-11 11:20am    
i cant understand the code provided by you sorry.....kindly help me to remove the error of open datareader and guide me the code for running the select and insert query for this code
What I usualy do and am not saying its the best, but I read stuff from the database and compare the stuff that i have with wat i want to insert. E.g i will check if the password does not exist in my database

 DataTable dTable = new DataTable();
dTable = systemBusinessLayer.GetAllEmployeesInfo();

C#
foreach (DataRow dRow in dTable.Rows)//Go through each row inside datatable
            {

                
    if (textBox1.Text== dRow["Password"].ToString())
                {
    MessageBox.Show("The password already exist");
                }
                 else
                    {
                       MessageBox.Show("The password does not exist");
                    }
            }


Now systemBusinessLayer is my Class where you can find the method getAuthentication()

public DataTable getAuthentication()
       {
           using (SqlConnection con = new SqlConnection(ConnString))
           {
               SqlCommand cmd = new SqlCommand("procGetLoginDetails", con);
               cmd.CommandType = CommandType.StoredProcedure;


               DataTable dTable = new DataTable();
               SqlDataAdapter adapter = new SqlDataAdapter(cmd);
               adapter.SelectCommand = cmd;
               adapter.Fill(dTable);

               return dTable;


           }


       }


then
procGetLoginDetails
is my storedprocedure that has the sql query.

Hope it helps...
 
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