Read column from Sql and populate to listbox - c#

I'm having problem with my sql query.
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
rd.Read();
ddl1.Items.Add(rd.GetValue(0).ToString());
conn.Close();
So it should return all cars from tbl1 that belongs to Bob. Query only return one string and put it into Listbox "ddl1" while it should return at least 3 of them.
Any ideas?

You need to loop through the reader:
while (rd.Read()){
ddl1.Items.Add(rd.GetValue(0).ToString());
}

Novak, not sure what your issue was with Curt's solution, as it is correct. Your complete statement should look like:
string connectionString= "Data Source=.\\SQLExpress;Trusted_Connection=True;User Instance=True;AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string query = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ddl1.Items.Add(reader.GetValue(0).ToString());
}
}
}
}

try below code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
ddl1.DataSource = rd;
ddl1..DataTextField = "columnname"; //your column name
ddl1.DataValueField = "columnname";
ddl1.DataBind();
rd.Close();
conn.Close();

Related

How to Save 2 different Cell values into 2 different variables from database C#

I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}

deleting from DB using a dropdownlist

hi im using a dropdownlist to get id from a table and then delete the line with a delete buton when i run the page teh dropdownlist get all the id's in the table all fine but when i delete it always delete the last id even if i select another
List<classe_cv_langues> li6 = new List<classe_cv_langues>();
SqlConnection con4 = new SqlConnection(#"Data Source=p5-pc\sqlexpress;Initial Catalog=recrutement_online_3;Integrated Security=True");
SqlCommand cmd4 = new SqlCommand();
cmd4.Connection = con4;
con4.Open();
cmd4.CommandText = "select id from cv_langues as cl inner join cv as c on cl.id_cv = c.id_cv where id_candidat= " + Session["Id_candidat"];
SqlDataReader dr4 = cmd4.ExecuteReader();
while (dr4.Read())
{
classe_cv_langues p6 = new classe_cv_langues();
p6.Id = int.Parse(dr4[0].ToString());
li6.Add(p6);
}
dr4.Close();
con4.Close();
DropDownList7.DataSource = li6;
DropDownList7.DataTextField = "id";
DropDownList7.DataValueField ="id";
DropDownList7.DataBind()
the delete buton:
SqlConnection con = new SqlConnection(#"Data Source=p5-pc\sqlexpress;Initial Catalog=recrutement_online_3;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "delete from cv_langues where id='"+DropDownList7.SelectedValue+"'";
cmd.ExecuteNonQuery();
con.Close();
Server.Transfer("gestion_cv.aspx");
Assuming your binding logic is on page_load method. Try testing for Page.IsPostBack
if (!Page.IsPostBack)
{
List<classe_cv_langues> li6 = new List<classe_cv_langues>();
SqlConnection con4 = new SqlConnection(#"Data Source=p5-pc\sqlexpress;Initial Catalog=recrutement_online_3;Integrated Security=True");
SqlCommand cmd4 = new SqlCommand();
cmd4.Connection = con4;
con4.Open();
cmd4.CommandText = "select id from cv_langues as cl inner join cv as c on cl.id_cv = c.id_cv where id_candidat= " + Session["Id_candidat"];
SqlDataReader dr4 = cmd4.ExecuteReader();
while (dr4.Read())
{
classe_cv_langues p6 = new classe_cv_langues();
p6.Id = int.Parse(dr4[0].ToString());
li6.Add(p6);
}
dr4.Close();
con4.Close();
DropDownList7.DataSource = li6;
DropDownList7.DataTextField = "id";
DropDownList7.DataValueField ="id";
DropDownList7.DataBind()
}

Error while query a Textbox

This should be a simple solution but Visual Studio 2012 give me errors that say sqlCon is a field but is used like a type and the same error for Textbox1... Maybe I am missing an assembly reference or proper connection imports? I'm looking to continue this simple route.
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
sqlCon.Connection = sqlCon;
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
Open the connection
use using statements
use Try-catch block
Snippet,
string connStr = "Server=***;Port=***;Database=***;Uid=***;Pwd=***;";
string query = "SELECT count(Dues) From Students";
using(MySqlConnection sqlCon = new MySqlConnection(connStr))
{
using(MySqlCommand sqlComm = new MySqlCommand())
{
sqlComm.Connection = sqlCon;
sqlComm.CommandText = query;
try
{
sqlCon.Open();
TextBox1.Text = sqlComm.ExecuteScalar().ToString();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
//sqlCon is of type MySqlConnection which is derived from DbConnection
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
//sqlCon has no Connection property, and why are you even assigning sqlCon to that property
sqlCon.Connection = sqlCon;
//ofcourse this will fail
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
I believe what you're trying to achieve is:
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand command = new MySqlCommand ("SELECT count(Dues) From Students");
try
{
sqlCon.Open();
command.Connection = sqlCon;
TextBox1.Text = command.ExecuteScalar().ToString();
}
finally
{
sqlCon.Close();
}

How list items from table with wildcard in sqlite using c#?

How can I get elements from table using wildcard?
I've made code something like that.
What is wron here? Is it safe if I put this into loop ?
private void Pokaz()
{
String sql = "SELECT [element] FROM [table] LIKE #Word";
SQLiteConnection connection = new SQLiteConnection(#"Data Source=C:\Temp2\dictionary.s3db");
connection.Open();
SQLiteCommand cmd = new SQLiteCommand(connection);
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
DataTable dt = new DataTable();
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
connection.Close();
dataGridView1.DataSource = dt;
}
I changed to String sql = "SELECT [element] FROM [table] where [element] LIKE \'#Word\'";
But now I get empty result.
I tried also this method. Fixed and works. Still above not.
List<string> list = new List<string>();
string connectionString = #"Data Source=C:\Temp2\dictionary.s3db";
string sql = "SELECT [element] FROM [table] where [element] LIKE \'%dog%\' ";
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(sql, connection))
{
connection.Open();
SQLiteDataReader rd = command.ExecuteReader();
while (rd.Read())
{
list.Add(rd[0].ToString());
}
}
}
Have you tried
String insSQL = "SELECT [element] FROM [table] like #Word"; //% search with prefix and postfix
SQLiteCommand cmd = new SQLiteCommand(insSQL);
cmd.Parameters.AddWithValue("#Word", "%" + "dog" + "%");
?

Problem with usage of multiple DataReaders in ASP.NET(C#)

SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
while (reader.Read())
{
string s = reader["Role"].ToString();
}
reader.Close();
conn1.Close();
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
if(s.Equals("teacher"))
{
GridView2.DataSource = rdr;
GridView2.DataBind();
}
rdr.Close();
//reader.Close();
}
catch
{
conn.Close();
}
I'm getting error in the below connection saying s does not exist in the current context. How to use the multiple datareaders please help me.
Declare string s out of hte loop
string s;
while (reader.Read())
{
s = reader["Role"].ToString();
}
SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
string s = String.Empty;
while (reader.Read())
s = reader["Role"].ToString();

Categories