C# query to combo box - c#

I am using a combo box to receive data from the ROnumber column upon form load. I would like to see the data from largest number to smallest in the combo box. This is the query I am using. This does work but it does not put it in any certain order.
string query = "select * from Inventory where ORDER BY ROnumber DESC ='" + comboRO.Text + "'";

I suggest you to use parameterized query instead for this; you can use like the following:
String sql = "select * from Inventory where someColumnName=#foo ORDER BY ROnumber DESC";
using (SqlConnection cn = new SqlConnection("Your connection string here"))
{
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#foo", SqlDbType.VarChar, 50).Value = comboRO.Text;
//execute command here
}
}
You have to give a valid column name instead for someColumnName

Related

C# : querying multiple columns into textboxes

This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().

How to Display data on a Label using MS Access Database in C#

I tried to get the balance and customer name to show up on the labels by getting user's input the customers ID on textbox1. But every time i tried to input the ID even just the first digit of the ID, it already shows error "Data type mismatch in criteria expression".
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string sql = "SELECT * FROM Customer WHERE ID= '" +textBox1.Text+ "'";
cmd.CommandText = sql;
OleDbDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
labelbalance.Text = reader["Balance"].ToString();
labelname.Text = reader["Firstname"].ToString() + reader["Lastname"].ToString();
}
Remove the single quotes around Id:
string sql = "SELECT * FROM Customer WHERE ID= " + textBox1.Text;
Because you have the quotes, ID is interpreted as character.
Update
As suggested in the comment, rather use parametrized query and avoid sql injection:
string sql = "SELECT * FROM Customer WHERE ID= #var";
cmd.CommandText = sql;
cmd.Parameters.Add(new OleDbParameter("#var", int.Parse(textBox1.Text));

Getting value from a database using textbox

string que = "SELECT Name FROM StudentInfo where StudentNo=textBox1.Text ";
Every time I run this it always says that
"The multi-part identifier "textBox1.Text" could not be bound".
How do I fix this?
You need to make the query include the value from the textbox. SQL Server doesn't know anything about your textbox - you've just provided the text textBox1.Text as if it refers to something that SQL Server knows about. However, you shouldn't include the value from your textbox in the SQL itself...
Instead, you should parameterize your SQL, and set the parameter from your textbox as a value to be sent alongside the SQL when you execute the query:
// Assuming an open connection...
int studentNo = int.Parse(textBox1.Text);
string sql = "SELECT Name FROM StudentInfo where StudentNo=#student_no";
using (var command = new SqlCommand(conn, sql))
{
command.Parameters.Add("#student_no", SqlDbType.Int).Value = studentNo;
// Execute the command as normal
}
This assumes that the type of StudentNo in your database is Int, of course - adjust accordingly (along with what you do with textBox1.Text - I'm currently parsing it as an int).
You should always parameterize your SQL rather than trying include the value within the SQL itself, for three important reasons:
It protects against SQL Injection Attacks
It avoids unnecessary conversions, and gives you more control over the conversions you do need
It typically makes it easier to read the SQL (as there isn't string concatenation code etc involved) so you can find issues with that more simply
You should be parameterizing your query:
string que = "SELECT Name FROM StudentInfo WHERE StudentNo = #StudentNo"
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#StudentNo", SqlDbType.VarChar, 50).Value = textBox1.Text;
//If StudentNo is Int
//command.Parameters.Add("#StudentNo", SqlDbType.Int).Value = (int) textBox1.Text;
connection.Open();
string veri = Convert.ToString(command.ExecuteScalar());
return veri;
}
}
Use this :
string strQuery = "SELECT Name FROM StudentInfo where StudentNo= #studentno";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#studentno", textBox1.Text.Trim());
I really dont understand your question but the query should be
string que = "SELECT Name FROM StudentInfo where StudentNo= '" + textBox1.Text + "';";
If the StudentNo is Varchar in the DB. or else
string que = "SELECT Name FROM StudentInfo where StudentNo=" + textBox1.Text + ";";
Where as you should go for parameterized query like this
using (SqlCommand command = new SqlCommand(
"SELECT Name FROM StudentInfo where StudentNo=#No", connection))
{
command.Parameters.Add(new SqlParameter("No", textBox1.Text));
SqlDataReader reader = command.ExecuteReader();
}

loop through all values in sql table using sql data reader

I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!

Dynamically passing a value inside a query?

I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}

Categories