MultipleActiveResultSets enabled but not working - c#

I enabled MARS and still cant execute two SqlDataReaders in one connection,i searched for a solution to enable MARS by default using RegEdit by couldnt find any solution and still getting that error : There is already an open DataReader associated with this Command which must be closed first.
Here is the code :
public partial class student_Courses : System.Web.UI.Page
{
string connectionString = "";
string query1 = "";
string query2 = "";
string courseName = "";
string chapterName = "";
string chapterVideoName = "";
string courseValue = "";
SqlDataReader sr2 = null;
protected void Page_Load(object sender, EventArgs e)
{
query1 = "SELECT * FROM Courses";
query2 = "SELECT * FROM Chapters WHERE value='" + courseValue + "'";
connectionString = "Data Source=Prince-PC;" +
"Initial Catalog=Elearning;" +
"Integrated Security=True;"+
"MultipleActiveResultSets=True";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command1 = new SqlCommand(query1, con);
SqlCommand command2 = new SqlCommand(query2, con);
if (con.State == ConnectionState.Closed)
con.Open();
using (SqlDataReader sr1 = command1.ExecuteReader())
{
while (sr1.Read())
{
courseName = sr1["name"].ToString();
courseValue = sr1["value"].ToString();
sr2 = command2.ExecuteReader();
while (sr2.Read())
{
chapterName = TextBox3.Text = sr2["name"].ToString();
chapterVideoName = Label2.Text = sr2["video_name"].ToString();
}
}
}
con.Close();
}
}

You need to dispose of sr2 via a using statement as done in this MSDN MARS example
// The following line of code requires
// a MARS-enabled connection.
productReader = productCmd.ExecuteReader();
using (productReader)
{
while (productReader.Read())
{
Console.WriteLine(" " +
productReader["Name"].ToString());
}
}

Related

How can i update data in c#

I'm working in Visual Studio 2019 In c
I have problem with updating data to database
I use local Visual Studio SQL database
private void button1_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
label5.Text = (dr["Kor"].ToString());
int s = 11;
string y = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
x = Int32.Parse(label4.Text);
x = x + 0;
label6.Text = (x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
x = x + 1;
label6.Text = (x.ToString());
String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
}
Add these lines
SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();
Please put a breakpoint and check the value of st, is it generating the valid query.
I would suggest to use parameterized query to avoid sql injection.
Also, please avoid using Select *, please use columns.

How can I receive a set of data from a query while sending a parameter in C#?

I get an exception I don't understand:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Clienti'.'
This is my code leading up to the error:
string connectionString = #"Data Source=VONWOLFENSPC\MSSQLSERVER01;Initial Catalog=Gestionare_excursii_agentie_turism;Integrated Security=True";
SqlConnection sqlCon = new SqlConnection(connectionString: connectionString);
string selectsql = "Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, " +
"G.ClientID, G.Sex, " +
"(Select E.Nume From Excursii E where E.ExcursieID LIKE G.ExcursieID) AS Excursie" +
"From Clienti G Where G.CNP Like #cnp";
SqlCommand cmd = new SqlCommand(selectsql, sqlCon);
cmd.Parameters.AddWithValue("#cnp", comboBox2.Text);
try
{
sqlCon.Open();
// error happens on the next line
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
//...
}
}
}
finally
{
sqlCon.Close();
}
How can I fix it?
Instead of concatenating the query, use a multi-line string literal:
string selectsql = #"
Select G.Nume, G.Prenume, G.Telefon, G.NumarInsotitori, G.ClientID, G.Sex,
(
Select E.Nume
From Excursii E
where E.ExcursieID LIKE G.ExcursieID
) AS Excursie
From Clienti G
Where G.CNP Like #cnp
";
Which you can paste directly to/from a SSMS query window for testing.
The issue you have is just spaces, if you tried to recheck the string you'll notice a missing space before FROM.
Also, you need to use using
string selectsql = #"SELECT
G.Nume
, G.Prenume
, G.Telefon
, G.NumarInsotitori
, G.ClientID
, G.Sex
, (SELECT E.Nume FROM Excursii E WHERE E.ExcursieID LIKE G.ExcursieID) AS Excursie
FROM
Clienti G
WHERE
G.CNP LIKE #cnp";
using(SqlConnection sqlCon = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(selectsql, sqlCon) )
using(SqlDataReader read = cmd.ExecuteReader())
{
cmd.Parameters.AddWithValue("#cnp", comboBox2.Text);
sqlCon.Open();
while(read.Read())
{
textBox1.Text = (read["Nume"].ToString());
textBox2.Text = (read["Prenume"].ToString());
textBox3.Text = (read["Telefon"].ToString());
textBox4.Text = (read["NumarInsotitori"].ToString());
textBox5.Text = (read["ClientID"].ToString());
comboBox1.Text = (read["Excursie"].ToString());
string sex = (read["Sex"].ToString());
if (sex == "M")
{
checkBox1.Checked = true;
checkBox2.Checked = false;
}
else
{
checkBox2.Checked = true;
checkBox1.Checked = false;
}
}
}

"ExecuteReader:Connection Property has not been initialized."

private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}

ASP.NET Gridview not outputting all data for a specific query

They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.

text.box blocked to prevent user answer again but if already answered show the data storage

I have this in my behind code:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
if (!IsPostBack)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
int totalRegistos = (int)myCommand.ExecuteScalar();
if (totalRegistos > 0)
{
// Já registado
Label1.Text = "The user already answered before.";
business.Enabled = false;
business2.Enabled = false;
mobile.Enabled = false;
Button1.Visible = false;
}
}
}
It's possible, in the text.box I get the data saved in the access db?
For example in mobile.Enabled = false; appears blocked/deactivate yes but with the data of the database inside.
How can I change my code to do such thing? display what I answered.
Try using a data reader to see if the returned data contains any rows.
protected void Page_Load(object sender, EventArgs e)
{
username.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
if (!IsPostBack)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
OleDbDataReader reader = myCommand.ExecuteReader();
if (reader.HasRows)
{
// Já registado
Label1.Text = "The user already answered before.";
business.Enabled = false;
business2.Enabled = false;
mobile.Enabled = false;
mobile.Text = ""; //if this is a textbox
Button1.Visible = false;
}
}
}

Categories