System.Data.OleDb.OleDbException: 'Cannot open any more tables' - c#

While my program was normally running in Visual Studio 2017 I closed it and reopened it and from that moment I am getting the error message "System.Data.OleDb.OleDbException: 'Cannot open any more tables.'" in the line with bold letters. My code is connected to a Microsoft Access database. Can you help me, please? It is for my thesis and I am in a real need for your help.
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
label.Content = "Ερώτηση " + Question;
var DBPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Database\\Users.mdb";
conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DBPath);
conn.Open();
id = MainWindow.id;
OleDbDataReader dr1 = null;
do
{
rInt = r.Next(1, 20);
cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID="+rInt+"; ");
cmd.Connection = conn;
**dr1 = cmd.ExecuteReader();**

Based on your code, I think you are filtering the data from the database by using the radom number.
If you want to use OleDbDataReader to get data from database, I suggest that you use the while(dr1.read()) instead of do.. while.
I modify some code and here is a code example you can refer to.
Code:
var conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DBPath);
conn.Open();
int rInt = 0;
Random random = new Random();
rInt = random.Next(1, 20);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID=" + rInt + "; ",conn);
OleDbDataReader dr1 = cmd.ExecuteReader();
string result = string.Empty;
while(dr1.Read())
{
result = dr1["Question"].ToString();
MessageBox.Show(result);
}
conn.Close();

I want to thank you all for your solutions but the problem was here
OleDbCommand cmd = new OleDbCommand("SELECT * FROM TestQuestions WHERE Chapter='Eisagogi' AND ID=" + rInt + "; ",conn);
I had changed the name Eisagogi in the database so as a result, the 'do...while' command was never finishing.

Related

prevent duplicate data from Excel to db via Oledb c#

I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.

showing line by line in Multi Line Textbox

When I search for phone number, it shows it line by line in DataGridView, but in my TextBox it shows it one beside one. Do you know why?
var con = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ Application.StartupPath + "\\db\\it.accdb");
con.Open();
var cmd = new OleDbCommand
{
CommandType = CommandType.Text,
CommandText = "select * from data where [ID] like(" + textBox9.Text + ")",
Connection = con,
};
var reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox20.Text = reader["Description"].ToString();
}
con.Close();

DataReader exception in C#

Let me first explain my code.
fetch fare for selected destination(reader1)
fetch * for selected user id(reader2)
insert data to process new balance(cmd3)
retrieve new balance as calculated field (reader3)
update travel account (cmd5)
clear calc_tb for next customer input(cmd6)
My problem is while running, I get this error:
There is already an open DataReader associated with this Command which must be closed first.
How can I handle more than one DataReader accessing different tables?
Is DataReader similar to resultset in Java ?
I'm a beginner in coding.
string id,
destin, num;
id = txt_id.Text;
destin = cb_destin.Text;
num = cb_num.Text;
string sql1 = "SELECT fare FROM route_info WHERE route_name='" +destin + "' ";
string sql2 = "SELECT * FROM trav_acc WHERE user_id='" + id + "'";
con.Open();
cmd1 = new SqlCommand(sql1, con);
reader1 = cmd1.ExecuteReader();
while(reader1.Read())
{
string fare = (string)reader1["fare"];
cmd2 = new SqlCommand(sql2, con);
reader2 = cmd2.ExecuteReader();
string cur_bal = (string)reader2["cur_bal"];
reader2.Close();
string calc1 = "INSERT INTO calc_tb VALUES('" + cur_bal + "','" + num + "','" + fare + "')";
string calc2 = "SELECT cur_bal - (nof_tickets * fare) AS new_bal FROM calc_tb";
cmd3 = new SqlCommand(calc1, con);
cmd3.ExecuteNonQuery();
cmd4 = new SqlCommand(calc2, con);
reader3 = cmd4.ExecuteReader();
while(reader3.Read())
{
string new_bal = (string)reader3["new_bal"];
string update = "UPDATE trav_acc SET cur_bal='" + new_bal + "',last_bal='" + cur_bal + "' WHERE user_id='" + id + "' ";
cmd5 = new SqlCommand(update, con);
cmd5.ExecuteNonQuery();
string clear = "DELETE FROM calc_tb";
cmd6 = new SqlCommand(clear, con);
cmd6.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Thank you for using EasyTravel.Come again soon!");
}
It seems that reader3 and cmd4 are defined outside of the code you are showing us, but at least they are defined outside the loop for reader1. So if your reader1 contains more than one row, reader3 and cmd4 will be assigned again, but the "old" reader3 is never closed. Close reader3 when it's finished reading. Or use a using statement, which will take care of the closing automatically.
using (DataReader reader1 = cmd1.ExecuteReader()) {
....
while (reader1.Read()) {
....
using (DataReader reader3 = cmd4.ExecuteReader()) {
while (reader3.Read()) {
}
} //reader3 is closed here automatically
}
} //reader1 is closed here automatically
Furthermore, I'm not sure if I remember correctly, but I think it's not possible to have two open readers on the same connection. I may be wrong with this, though.

Why do I get a 'System.ArgumentOutOfRangeException' when setting the Text for a row cell?

Using a number of queries, as shown in the code below, I get the following exception:
An exception of type 'System.ArgumentOutOfRangeException' - Specified
argument was out of the range of valid values
on this line:
e.Row.Cells[3].Text = count;
What could be the problem? I tried countless different things, but I can't get it working. I am a novice at this.
SqlConnection conn;
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~\\App_Data\\ForumDB.mdf") + ";Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm;
comm = new SqlCommand("SELECT COUNT(ThreadId) FROM [Threads] WHERE [TopicId] = #TopicId", conn);
SqlCommand comm2;
comm2 = new SqlCommand("SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = #TopicId", conn);
SqlCommand comm3;
comm3 = new SqlCommand("SELECT PostedBy FROM Threads WHERE PostedDate=(SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = #TopicId", conn);
//FOR COMMAND1 CMD
comm.Parameters.Add("#TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm.Parameters["#TopicId"].Value = e.Row.Cells[0].Text;
string count = (comm.ExecuteScalar().ToString());
e.Row.Cells[3].Text = count;
//FOR COMMAND2 CMD1
comm2.Parameters.Add("#TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm2.Parameters["#TopicId"].Value = e.Row.Cells[0].Text;
string count1 = (comm2.ExecuteScalar().ToString());
e.Row.Cells[4].Text = count1;
//for command3 cmd2
comm3.Parameters.Add("#TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm3.Parameters["#TopicId"].Value = e.Row.Cells[0].Text;
if (comm3.ExecuteScalar() != null)
{
count2 = (comm3.ExecuteScalar().ToString());
}
conn.close();
The problem with this line:
e.Row.Cells[3].Text = count;
Appears to be that this row does not have 4 cells. Check it by putting a breakpoint on that line, and looking at the value of e.Row.Cells.Count. It will be smaller than 4.
Also, you may want to change how you are performing your queries, because it seems you can get all the fields you need in a single query, instead of three separate ones:
const string query =
"SELECT PostedBy, PostedDate, COUNT(ThreadId) AS Count " +
"FROM [Threads] WHERE [TopicId] = #TopicId " +
"ORDER BY PostedDate DESC " +
"LIMIT 1";
var fileToAttach = Server.MapPath("~\\App_Data\\ForumDB.mdf");
var connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + fileToAttach + ";Integrated Security=True;User Instance=True";
var topicId = int.Parse(e.Row.Cells[0].Text);
var postedBy = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn)
{
cmd.Parameters.AddWithValue("#TopicId", topicId);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// NOTE: I am assuming you have these cells now!
e.Row.Cells[3].Text = reader["Count"].ToString();
e.Row.Cells[4].Text = reader["PostedDate"].ToString();
postedBy = (string)reader["PostedBy"];
}
}
}
}

Want to create a comment system in asp.net

i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"

Categories