Populating textbox from after selecting value from comboBox - c#

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

Related

Connection is not closed properly ASP.NET C#

I have this button click event. Been trying to replace the con.Close() in different lines of code, tried for hours but couldn't fix. Maybe a second pair of eyes can help?
Error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
con.Open();
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
con.Close();
}
else
{
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
con.Open();
int i = cmd1.ExecuteNonQuery();
con.Close();
if (i != 0)
{
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
}
Try this (open connection only once and close only once):
protected void Button1_Click(object sender, EventArgs e) {
using(SqlConnection con = new SqlConnection()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
bool hasRows = reader.HasRows;
reader.Close();
if (hasRows) {
// This line makes no sense after the execution of the query.
//cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
} else {
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
int i = cmd1.ExecuteNonQuery();
if (i != 0) {
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
} else {
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
con.Close();
}
}
Now let's discuss this line
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
This let's attacker manipulate your input with sql injection. To solve this, use the same cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value); that you are using in the second query. The Session["id"] is somewhat safer as it is not provided by the user but better safe than sorry as the parameters sanitize the input and protect you from sql injection.

Trying to retrieve parameter value from another class library

I have created Member Maintenance Code in which I will retrieve the members ID,Name and all basic things
My code is as follows:
private void Mem_Maintenance_Load(object sender, EventArgs e)
{
try
{
txt_mem_id.Text = Generate_no.gen_no("MEM").ToString();
}
catch(Exception Ex)
{
MessageBox.Show("Error\n\n"+Ex.ToString());
}
}
I have created a ClassLibrary named Library Whose code is as follows
namespace LIBRARY
{
public class Generate_no
{
public static int gen_no(string P_PRM_TYPE)
{ OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\arekh\MS Access\soc_data.accdb;Persist Security Info=False;";
connection.Open();
int v_last_no = 0;
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = #"select PARM_VALUE from soc_parm_mast where PARM_TYPE = '" + P_PRM_TYPE + "';";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1;
reader.Close();
command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = " + P_PRM_TYPE + ";";
command.ExecuteNonQuery();
connection.Close();
return v_last_no;
}
}
}
But during execution an error is coming up
System.FormatException:Input string was not incorrect format at
LIBRARY.Generate_no.gen_no(String P_PRM_TYPE)
command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = '" + P_PRM_TYPE + "';";
You were missing the single quotation marks in the update statement
The Line v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1; causing the specified Error, The Int32.Parse will throw FormatException if the input is not convertible. So i strongly advise you to use Int32.TryParse(). Then the code will be like the following:
public static int gen_no(string P_PRM_TYPE)
{
using (OleDbConnection connection = new OleDbConnection(#"Connection string here"))
{
connection.Open();
int v_last_no = 0;
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
string query = #"select PARM_VALUE from soc_parm_mast where PARM_TYPE = #P_PRM_TYPE";
command.CommandText = query;
command.Parameters.AddWithValue("#P_PRM_TYPE", P_PRM_TYPE);
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
if (!Int32.TryParse(reader["PARM_VALUE"].ToString(), out v_last_no))
{
// Conversion failed, Show message if needed
// v_last_no will be 0
}
reader.Close();
}
using (OleDbCommand command = new OleDbCommand())
{
command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE =#P_PRM_TYPE";
command.Parameters.AddWithValue("#P_PRM_TYPE", P_PRM_TYPE);
command.ExecuteNonQuery();
}
}
return v_last_no;
}
One more advise for you : beware of SQL Injection while using the Concatenated string as queries. Use parameterized queries instead.

two queries in same method

I am trying to execute two queries in the same method but it gives me this exception. I can get red of this exception by declaring new command but is there any way to use the same command?
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();
You need to close your OleDbDataReader object when you are finished with it:
// previous code omitted for brevity
//
while (reader.Read())
{
id = reader[0].ToString();
}
// need to close reader
//
reader.Close();
// run your other query (omitted for brevity)
And as the comment on your question states, the way you construct your query is extremely vulnerable to a SQL inject attack. Parameterize your query the proper way.
As per Dmitry's comment, I completely agree. Wrap your OleDbDataReader object in a using block to call OleDbDataReader.Dispose() upon completion of the block:
using (OleDbDataReader reader = command1.ExecuteReader())
{
// ...
}
You need to close the reader after first execution,so code will be like this
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
////////code for closing the reader/////////////
reader.Close();
///////////////
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();

How to run multiple SQL commands in a single SQL connection?

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.

trouble updating to mysql inside reader loop

I am looping through these mysql rows and processing data. But, in part of the processing I am also wanting to update into the same mysql table.
This is not working for me.
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
CODE
string connString = "Server=localhost;Port=3306;Database=communications;Uid=myuser;password=mypass;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(reader["account"].ToString());
SendFax(reader["filepath"].ToString(), reader["filepath"].ToString(), reader["id"].ToString(), reader["fax"].ToString());
string id = reader["id"].ToString();
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
}
}
I think that last command.ExecuteReader() tries to open one more reader, but it is not possible to do with one connection. Close first open reader firstly, then modify this table; or try to use command.ExecuteNonQuery() method.

Categories