set Id equal to number contained in textbox - c#

Hi I want to fill a combo box with names from a table where id is the number contained in textbox.The txtPartId is populated from another page as is the name in txtPart. The error I get when I run this is "Invalid column name "txtPartId"
public ReList(string Str_value, string id)//declare value
{
InitializeComponent();
txtPart.Text = Str_value;
txtPartId.Text = id.ToString();
displayRe();
}
private void displayRe()
{
try
{
sc.Open();
string Query = "select * from Re where Part_PartID =txtPartId ";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string Name = dr.GetString(1);
cbRe.Items.Add(Name);//Displaying a list in the Combo Box
}
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The quick and dirty answer is to make the following change:
string Query = "select * from Re where Part_PartID = " + txtPartId.Text;
assuming Part_PartID is an integer.
If it is a string then you can use:
string Query = string.Format("select * from Re where Part_PartID = '{0}'", txtPartId.Text);
The compiler is not going to inject the value of the text in txtPartId into your query string for you.
However, that introduces the scope for SQL injection, so I strongly suggest you parameterize your query. There are many examples of this on SO.

Related

make many mysql command in one connection in c# visual studio & unknown column in where clause

I have mySql database contains ID, projectName, companyName, projectNum, .. etc
I need to create Combobox that display projectName (project name isn't unique)
when I try to execute this the following error appears:
"Unknown column 'proj2' in where clause"
even though when I try to print this value it prints successfully in my code.
so I changed to display ID in Combobox and works well
now I need if I choose one ID to fill some fields (projectName, companyName, projectNum) then display values in other Combobox (e.g Combobox2) it has item number which is not unique and it
depend on projectName field.
I try to make one connection and two connection but both of them didn't work.
nothing appears in Combobox2
when I try to choose ID from first Combobox the same error appears:
"Unknown column 'proj2' in where clause"
I don't know if should I change the design of the database.
again I should mention that project name, company name, project number may be repeated in more than 50 records.
below is the code
first function to fill the first Combobox:
private void Form2_Load(object sender, EventArgs e)
{
try
{
// String getQuery = "Select projectName From ubc.BOQ_Table Group By projectName";
String getQuery = "Select ID From ubc.BOQ_Table";
connection.Open();
MySqlCommand command = new MySqlCommand(getQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox1.Items.Add(reader.GetString("ID"));
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
second function to fill fields depend on choosing ID:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//get vaalue of selected project
selectedProject = comboBox1.SelectedItem.ToString();
String selectQuery = "Select * From ubc.BOQ_Table where ID=" + selectedProject;
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
projectNameText.Text = reader.GetString("projectName");
projectName = projectNameText.Text;
companyNameText.Text = reader.GetString("companyName");
projectNumber.Text = reader.GetInt32("projectNumber").ToString();
reader.Close();
}
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
command.ExecuteNonQuery();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox2.Items.Add(reader.GetString("itemNum"));
}
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
This line of code is causing the problem:
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
As commenters have mentioned, concatenating strings is causing both the syntax error and makes your code vulnerable to SQL injection attacks. The solution is to use "parameterized queries" by putting the variable in a MySqlParameter object.
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=#projectName;";
command.Parameters.AddWithValue("#projectName", projectName);
using (var reader = command.ExecuteReader())
{
// ...
(You may find some people saying "don't use AddWithValue", but that's an objection that applies just to SqlCommand; there's no good reason to avoid using it with MySqlCommand.)

Unknown column 'New' in 'field list' while using sql command in the asp.net

I trying to update a GridView using asp.net while updating I am passing the text box value but I am getting the above error.
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string Query = #"update app_order_master set order_amt=" + orderType + " where order_id=" + l1.Text;
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Try using parameters instead
Label l1 = g1.Rows[e.RowIndex].FindControl("idlbl") as Label;
TextBox t1 = g1.Rows[e.RowIndex].FindControl("typeText") as TextBox;
string orderType = t1.Text;
string order_id = l1.Text;
string Query = "update app_order_master set order_amt = #orderType where order_id = #order_id";
MySqlCommand cmd = new MySqlCommand(Query);
cmd.Parameters.Add("#orderType", orderType);
cmd.Parameters.Add("#order_id", order_id);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
Here is another example that might help you, a pointer that other developers have mentioned your original code is a probe to SQL injection if you bing search this, there are loads of examples that you can find of what SQL injection is. Here is my method that might assist you. A little code example to assist you.
public void updateProductTbl(string prodBrand, string description, decimal weight, decimal unitwholesaleprice, decimal unitretailprice, string prodImage, string location, string qrcode,
string barcode, string suppliercode, int unitinstock, int unitsonorder, int reorderlevel, bool discontinued, decimal unitofmeasure, string prodcategory, int OldValue)
{
query = #"update Product
SET
prod_band=#prodBrand
,prod_description=#description
,prod_weight=#weight
,prod_perUnitwholesalePrice=#unitwholesaleprice
,prod_perUnitRetailPrice = #unitretailprice
,prod_Image=#prodImage
,prod_location=#location
,prod_QRcode=#qrcode
,prod_barcode=#barcode
,prod_supplierFKCode=#suppliercode
,prod_unitsinstock=#unitinstock
,prod_unitsonorder=#unitonorder
,prod_reorderlevel=#reorderlevel
,prod_discontinued=#discontinued
,prod_unitofmeasure=#unittofmeasure
,prod_category=#prodcategory
where prod_rec_id=#OldValue";
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.Parameters.AddWithValue("#prodBrand", prodBrand);
myCommand.Parameters.AddWithValue("#description", description);
myCommand.Parameters.AddWithValue("#weight", weight);
myCommand.Parameters.AddWithValue("#unitwholesaleprice", unitwholesaleprice);
myCommand.Parameters.AddWithValue("#unitretailprice", unitretailprice);
myCommand.Parameters.AddWithValue("#prodImage", prodImage);
myCommand.Parameters.AddWithValue("#location", location);
myCommand.Parameters.AddWithValue("#qrcode", qrcode);
myCommand.Parameters.AddWithValue("#barcode", barcode);
myCommand.Parameters.AddWithValue("#suppliercode", suppliercode);
myCommand.Parameters.AddWithValue("#unitinstock", unitinstock);
myCommand.Parameters.AddWithValue("#unitonorder", unitsonorder);
myCommand.Parameters.AddWithValue("#reorderlevel", reorderlevel);
myCommand.Parameters.AddWithValue("#discontinued", discontinued);
myCommand.Parameters.AddWithValue("#unittofmeasure", unitofmeasure);
myCommand.Parameters.AddWithValue("#prodcategory", prodcategory);
myCommand.Parameters.AddWithValue("#OldValue", OldValue);
status = myCommand.ExecuteNonQuery(); // when ExecuteNonQuery method return 1 or 0 if it have saved to sql db
if (status > 0)
{
MessageBox.Show("Your Data has been updated", "Update Data", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch(Exception ex)
{
MessageBox.Show("SQL Error in Product Add method:"+ex.ToString(), "Warning Data not saved", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
myConn.Close();
}
}
Hope the abe gives you a good idea of how to go about SQl and passing params in a method.

How to print 2 columns retrieved from SQL Server database

Something missing with the code (I guess). I want to show the student id and name in the list box. But I see this:
I can't figure out the problems especially with the inner join.
private void button1_Click(object sender, EventArgs e)
{
string strName = "";
connect.Open();
SqlCommand command = new SqlCommand(" Select Student_tbl.StudentName, Student_tbl.StudentID, Module_tbl.ModuleID FROM[Course-Student] INNER JOIN Student_tbl ON [Course-Student].SID = Student_tbl.StudentID INNER JOIN Module_tbl ON[Course-Student].CID = Module_tbl.ModuleID WHERE(Module_tbl.ModuleID = '" + tbCourse.Text+"')",connect);
command.ExecuteNonQuery();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
strName = reader[1].ToString();
listBox1.Items.Add(strName);
}
connect.Close();
}
You are printing retrieving from the reader only the StudentID field. Change your while loop as follows to retrieve both fields and concatenate the values:
while (reader.Read())
{
var name = reader[0].ToString();
var id = reader[1].ToString();
listBox1.Items.Add(id + " " + name);
}
You can also use String Interpolation (which is C# 6 syntactic sugar for string.Format) like this:
while (reader.Read())
{
listBox1.Items.Add($"{reader[1].ToString()} {reader[0].ToString()}");
}
Also, as for the sql statement: Do not use string concatenation to create the statement. This is susceptible for SQL Injections. Use instead Parameterized Queries

DataReader IndexOutofRangeException was unhandled by user code

I ran into another issue again. I was trying to get data from the database using DataReader but I got the error when i was testing my code. Can anyone help me out? The error occurred at this line:
chkAssess = readAssess[columnName].ToString();
Below is the code snippet:
public string CheckAssess(string emailAddress, string columnName)
{
string chkAssess = "";
SqlDataReader readAssess;
//readAssess = new SqlDataReader();
string MgrAssessQry = "SELECT '"+columnName+"' FROM tblAllUsers";
//MgrAssessQry += " WHERE email ='" + emailAddress + "'";
SqlCommand cmdReadAssess = new SqlCommand(MgrAssessQry, cn);
cn.Open();
readAssess = cmdReadAssess.ExecuteReader();
while(readAssess.Read())
{
// Add the rows
chkAssess = readAssess[columnName].ToString();
}
return chkAssess;
}
try to use column name without ''
select something from table
instead of
select 'something' from table
for security reasons, don't create sql queries in that way (by concatenating strings) - use #parameters instead
2. close the reader at the end
Try this:
public string CheckAssess(string emailAddress, string columnName)
{
string chkAssess = "";
SqlDataReader readAssess;
//readAssess = new SqlDataReader();
string MgrAssessQry = "SELECT #Column_Name FROM tblAllUsers";
SqlCommand cmdReadAssess = new SqlCommand(MgrAssessQry, cn);
cmdReadAssess.Parameters.AddWithValue(new SqlParameter("Column_Name", columnName));
cn.Open();
readAssess = cmdReadAssess.ExecuteReader();
while(readAssess.Read())
{
// Add the rows
chkAssess = readAssess.GetString(0);
}
return chkAssess;
}
You have got several problems here.
Check whether your readAssess has rows like below.
if(readAssess.HasRows)
If it doesn't have rows then trying
chkAssess = readAssess.GetString(0);
would throw this error, as Arrays are index-based.
So your code should be like below
if(readAssess.HasRows)
{
while(readAssess.Read())
{
chkAssess = readAssess.GetString(0);
}
}
Other problem is you need to close both the reader & the connection afterwards.
readAssess.Close();
cn.Close();
Also your code is potentially vulnerable to SQL Injection.
if (reader.HasRows)
{
while (reader.Read())
{
int result = Convert.ToInt32(reader.GetString(0));
Console.WriteLine(result);
}
}
The most important thing is check the query first by executing in SQL Server and see if any result is coming or not.
Secondly based on the type of output you are receiving cast it to that particular data type (important).Mostly everyone is saving the data in varchar so.

SQL Syntax Error (INSERT command)

I have a form with a text box and button, such that when the user clicks the button, the specified name in the text box is added to a table in my sql database. The code for the button is as follows:
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
The class cSqlQuery is a simple class that executes various T-SQL actions for me and its code is as follows:
class cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
The class works well throughout my application so I don't think the error is in the class, but then I can't be sure.
When I click the button I get the following error message:
Incorrect syntax near =
Which is really annoying me, because when I run the exact same command in SQL Management Studio it works fine.
I'm sure I'm missing something rather simple, but after reading my code through many times, I'm struggling to see where I have gone wrong.
you have to remove = after values.
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES ('" + strNewDiaryItem + "');"
and try to use Parameterized queries to avoid Sql injection. use your code like this. Sql Parameters
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES (#DairyItem);"
YourCOmmandObj.Parameters.AddwithValue("#DairyItem",strNewDiaryIItem)
Remove the = after VALUES.
You do not need the =
A valid insert would look like
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Source: http://www.w3schools.com/sql/sql_insert.asp
Please use following:
insert into <table name> Values (value);
Remove "=", and also i would recommend you to use string.format() instead of string concatenation.
sqlText = string.format(INSERT INTO tblDiaryTypes (DiaryType) VALUES ('{0}'), strNewDiaryItem);"

Categories