Getting value from a database using textbox - c#

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

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

C# query to combo box

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

Getting Result From Select Command SQL Server

I am trying to get the result from a select command:
string strName = dtTable.Rows[i][myName].ToString();
string selectBrand = "SELECT [brand] FROM [myTable] WHERE [myName] = '" + strName + "'";
SqlCommand sqlCmdSelectBrand = new SqlCommand(selectBrand , sqlConn);
sqlCmdSelectBrand .Connection.Open();
sqlCmdSelectBrand .ExecuteNonQuery();
string newBrand = Convert.ToString(sqlCmdSelectBrand .ExecuteScalar());
sqlCmdSelectBrand .Connection.Close();
The select works, I have executed it in SQL Studio, but it does not assign to my variable on the second to last line. Nothing gets assigned to that variable when I debug it...
Any advice?
Your approach to read data returned from a SELECT query is (in this particular context) a bit wrong. Usually you call ExecuteReader of the SqlCommand instance to get back your data.
string strName = dtTable.Rows[i][myName].ToString();
string selectBrand = "SELECT [brand] FROM [myTable] WHERE [myName] = #name";
using(SqlCommand sqlCmdSelectBrand = new SqlCommand(selectBrand , sqlConn))
{
sqlCmdSelectBrand.Parameters.Add(
new SqlParameter("#name", SqlDbType.NVarChar)).Value = strName;
sqlCmdSelectBrand .Connection.Open();
using(SqlDataReader reader = sqlCmdSelectBrand.ExecuteReader())
{
if(reader.HasRows)
{
reader.Read();
string newBrand = reader.GetString(reader.GetOrdinal("Brand"));
..... work with the string newBrand....
}
else
// Message for data not found...
sqlCmdSelectBrand .Connection.Close();
}
}
In your context, the call to ExecuteNonQuery is not required because it doesn't return anything from a SELECT query. The call to ExecuteScalar should work if you have at least one record that match to the WHERE condition
Notice also that you should always use a parameterized query when building an sql command text. Also if you think to have full control of the inputs, concatenating string is the open door to Sql Injection

Editing data into SQL with C#

I have this method for Editing data but I don't know how to write the code... Until now I have this which I don't really understand and I have an error in it. It says incorrect syntax near '('.
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand(
"UPDATE Members SET (Name, Surname, EntryDate) VALUES('" + Name + "','" + Surname + "','" + EntryDate + "')' WHERE'(' Id '='" + member.Id + "')",
sqlConnection);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
The problem is when I start to write WHERE
Help please.
Please read all of this answer, not just the first part
There are multiple issues here. The most immediate problem is here:
"')' WHERE'('
That's acting as if you're trying to quote the bracket. That "should" be:
"') WHERE ('
At that point it would look like a valid (but bad) INSERT command... but your use of VALUES which doesn't look like it's a valid way of updating in T-SQL anyway.
However, you shouldn't use this approach at all. It's error-prone, hard to read, and most importantly prone to SQL injection attacks.
Instead, you should use parameterized SQL:
string sql = #"UPDATE Members
SET Name = #Name, Surname = #Surname, EntryDate = #EntryDate
WHERE Id = #Id";
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Name", SqlDbType.NVarChar).Value = member.Name;
command.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = member.Surname;
command.Parameters.Add("#EntryDate", SqlDbType.DateTime).Value = member.EntryDate;
command.Parameters.Add("#Id", SqlDbType.NVarChar).Value = member.Id;
int rows = command.ExecuteNonQuery();
// TODO: Work out what to do if rows isn't 1
}
}
(With adjustments for the appropriate data types, of course.)
You should NEVER EVER concatenate together your SQL statements with user input.
Instead : use parametrized queries - they're easy to use, avoid SQL injection, and improve performance.
Try code something like this:
string updateStmt = "UPDATE dbo.Members SET Name = #Name, Surname = #Surname, EntryDate = #EntryDate WHERE Id = #ID";
sqlCommand = new SqlCommand(updateStmt, sqlConnection);
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name;
sqlCommand.Parameters.Add("#Surname", SqlDbType.VarChar, 100).Value = surname;
sqlCommand.Parameters.Add("#EntryDate", SqlDbType.DateTime).Value = entrydate;
sqlCommand.Parameters.Add("#ID", SqlDbType.Int).Value = member.Id;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
The correct syntax for an update statement is
"UPDATE Members SET Name = #name, Surname = #surname, EntryDate = #date WHERE id=#id"
Said that, you should use parameterized query like this
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand("UPDATE Members SET Name = #name, Surname = #surname, " +
"EntryDate = #date " +
"WHERE Id = #id", sqlConnection);
sqlCommand.Parameters.AddWithValue("#name", Name);
sqlCommand.Parameters.AddWithValue("#surname", Surname);
sqlCommand.Parameters.AddWithValue("#date", EntryDate);
sqlCommand.Parameters.AddWithValue("#id", Status);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
As a side note, keep in mind that AddWithValue is a simple way to add parameters to you query, but if the perfomance of this query is critical it is better to use a fully defined parameter with the datatype that matches exactly your database column's type and with the exact size.
Remove the quotes from around the WHERE and you should be fine. Please heed the warnings given in the comments about SQL injection attacks.
Your code has syntax error for update and also SQLInjection issue.
You need to pass parameters to update query rather than passing direct values.
It should be as follows:
public void EditMember(Member member)
{
string Name = member.Name;
string Surname = member.Surname;
string EntryDate = member.EntryDate.ToString("dd.MM.yyyy");
string Status = member.Status;
sqlConnection.Open();
sqlCommand = new SqlCommand("UPDATE Members SET Name=#Name, Surname=#Sirname, EntryDate=#EntryDate WHERE Id = #id", sqlConnection);
sqlCommand.parameters.AddparameterWithValue("#Name",Name);
sqlCommand.parameters.AddparameterWithValue("#Surname",Surname);
sqlCommand.parameters.AddparameterWithValue("#EntryDate",EntryDate);
sqlCommand.parameters.AddparameterWithValue("#Id",Id);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
Edit the post to make correct answer:
i.e. you don't need brackets in where clause. And yes the better query is
"UPDATE Members SET Name=#Name, Surname=#Surname, EntryDate=#EntryDate WHERE Id=#ID"
and then you add #Name, #Surname, .. etc through parameter of command object.

Categories