showing line by line in Multi Line Textbox - c#

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();

Related

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

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.

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.

Populating textbox from after selecting value from comboBox

I am trying to populate my textbox after selecting a value from my comboBox.
My code is running fine, I don't have any errors when I run it but when I select a value from my comboBox, it's not populating my textbox. See my code below.
private OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
}
private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
command.CommandText = query;
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Two immediate issues that I see:
You are populating the CommandText property of the OleDbCommand object after issuing the ExecuteReader method, meaning there is no SQL statement being evaluated.
The SQL statement should be populated before the ExecuteReader method is issued, i.e.:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
The where clause of your SQL statement assumes that patientNo contains string data, which could be incorrect given the name of this field.
Just found out the issue. Had the wrong value to compare my Lastname.Text with and fixed the code's arrangement. Thanks for all your help everyone.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();

Database dropdown list value printed on labels

I'm using ASP.net to make a dropdown menu. The dropdown menu is linked to a database, all that works. If a value is selected in the dropdown, labels have to be filled that match the dropdown value in the database.
Hope I'm being clear, here's what I have so far :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
Unfortunately this leaves the labels empty. If I add the function to my page_load the labels do get filled, but for some reason only by the first value in the dropdown. A similair post on here suggested shoving it in the selectindexchanged, but that leaves it empty for me. Anyone got an idea?
Here's my page_load event right now
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}
In your load event AND your code in the dropdown_selectedindexchanged, check the IsPostBack of the page. Ex :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
}
}
Load :
if (!IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}
}
Please check that the AutoPostBack property of the DropDownList1 is set to True.

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"];
}
}
}
}

Categories