Dropdownlist data not insert in query - c#

I select the DropDownList value to insert in query but the value remains blank in query and due to empty value in where condition not any result outcome. I do with different tricks but remain empty
if (chkBoxChanl.Checked)
{
sql += " and channelName = '" + ddlChannel.Text + "' ";
}
if (chkBoxDate.Checked)
{
sql += " and transmissionDate_ between '" + tbFrom.Text + "' and '" + tbTo.Text + "'";
}
if (chkBoxProgrm.Checked)
{
sql += " and programName ='" + ddlProgram.Text + "'";
}
if (chkBoxParty.Checked)
{
sql += " and partiesName like '%" + ddlParty.SelectedValue + "%'";
}
if (chkBoxPerson.Checked)
{
sql += " and personsName like '%" + ddlPerson.SelectedItem + "%'";
}
if (chkBoxProvince.Checked)
{
sql += " and ProvinceName like '%" + ddlProvince.SelectedItem + "%'";
}
if (chkBoxCity.Checked)
{
sql += " and CityName like '%" + ddlCity.Text + "%'";
}
Like
ddlProgram.Text
ddlProvince.SelectedItem
ddlPerson.SelectedValue
selected DropDownList value is shown empty in query.
What can I do to add the selected value in query? Please help me!
I check that when I select the dropdownist values which come on first load then 2md time after press search button dropdownlist values empty and when I press search button it first run Page_Load function and if(!IspostBack) is execute then all dropdownlist selected values become empty which cause to empty values in where clause. Now I want that when I press search button dropdownlist values remain loaded which will resolve the issue to become enpty dropdownlist values. Please guide me further

First of all: you shouldn't concatenate parameters to queries in this way. You expose yourself to SQL injection attacks.
Sorry, new to stackoverflow. Didn't see the comment button
and
programName =' mytext' OR 1 = 1;
DROP Database
Comment anything else.

You cannot concatenate your input field's values directly in your sql query. It makes your system vulnerable to Sql Injection. You should at least encode what you are retrieving from these fields before running such sql query. It is very important that you read this before going ahead.
After reading the above carefully, you can get the value of the selected item on your dropdown. You do this:
yourDropDown.SelectedItem.Value
If it does not return a value, that's probably because you didn't set any value in your dropdown. Remember to set it according to your datasource:
yourDropDown.DataValueField = "TheSourceFieldContainingTheValue";

Build your sql query something like this :
public DataSet ExecuteDataSet(string text, SqlParameter[] paramList)
{
using (SqlCommand sqlCommand = new SqlCommand(text, sqlConnection))
{
if (paramList != null)
{
foreach (var param in paramList)
{
sqlCommand.Parameters.Add(param);
}
}
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataSet dataSet=new DataSet();
dataAdapter.Fill(dataSet);
return dataSet;
}
}

Related

Updating SQL database entries

I'm currently attempting to introduce an update option for my form project. I can successfully save entries to the database, but I want to be able to update these entries if the user gets information in the future that needs to be updated within the database...
Currently my error is, "You have an error in your SQL syntax; check the manual that corresponds to your MYSQL server version for the right syntax to use near'"lossID=8, 25 Oct, 00:00, 25 Oct, 23:59,","" at line 1.
I thought this would be from perhaps the set syntax but I get the same error if I remove it or change anything there. I'm not sure if its because I am using parameters for my insert function, and perhaps just missing something?
My code for this is,
if (start_time.Text == end_time.Text)
{
MessageBox.Show("Please input a different ending time for the loss event");
}
else
{
string constring = "datasource=localhost;port=3306;username=root;password=1234; ";
string query = "update lossdatabase.losstable set (lossID= '" + this.textBox1.Text + "', #Start, #Start_Time, #End, #End_Time, #Equipment, #Event, #Responsibility, #Cause, #Reason, Capacity_Loss='" + capacity + "', Planned= '" + Planned + "', Scheduled='" + Scheduled + "', Prepared='" + Prepared + "', #Primary_Rate, #Primary_Volume, #Primary_Percentage, #Secondary_Rate, #Secondary_Volume, #Secondary_Percentage, #Comment) where lossID= '" + this.textBox1.Text + "' ;";
//Defines the connection string to allow data to be deposited into the database, along with defining the variables and columns for the data to be added to
MySqlConnection conLossDB = new MySqlConnection(constring);
MySqlCommand cmdLossDB = new MySqlCommand(query, conLossDB);
cmdLossDB.Parameters.AddWithValue("#Start", start_date.Text);
cmdLossDB.Parameters.AddWithValue("#Start_Time", start_time.Text);
cmdLossDB.Parameters.AddWithValue("#End", end_date.Text);
cmdLossDB.Parameters.AddWithValue("#End_Time", end_time.Text);
cmdLossDB.Parameters.AddWithValue("#Equipment", comboBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Event", comboBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Responsibility", comboBox3.Text);
cmdLossDB.Parameters.AddWithValue("#Cause", richTextBox1.Text);
cmdLossDB.Parameters.AddWithValue("#Reason", richTextBox2.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Rate", Rate_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Volume", Volume_box.Text);
cmdLossDB.Parameters.AddWithValue("#Primary_Percentage", Percentage_box.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Rate", Rate_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Volume", Volume_2.Text);
cmdLossDB.Parameters.AddWithValue("#Secondary_Percentage", Percentage_2.Text);
cmdLossDB.Parameters.AddWithValue("#Comment", richTextBox3.Text);
//Defines which boxes to read in order to input the text from the defined boxes into the corresponding columns
MySqlDataReader myReader;
try
{
conLossDB.Open();
myReader = cmdLossDB.ExecuteReader();
MessageBox.Show("The loss entry has successfully been updated");
//Opens the database and carries out the defined command outlined in the code above
this.Close();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

DataSet coming as Empty

I have a method called searchDB that search the database according to keyword typed by user.
I am storing the search results in DataSet. This method search in only one column.
public DataSet searchDB(string identifier)
{
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'";
//string sql = "SELECT [identifier] FROM [Category3]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "identifier");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
else
return dataSet;
}
The variable "identifier" gets value from the textbox.
Suppose, when i pass "windows" as value for variable, it should return 1 row.
But when i put breakpoint, it is hitting the if condition
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
and returning 0 rows.
Can anyone point out my mistake.
You seem to be using the SQL LIKE wrong (unless your identifier column really ends with an asterisk):
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'
Like uses the % character for wildcard, instead of *, so try:
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "%'
Edit: I didn't see that the question concerns MS Access, but the answer holds true still. See the following SO question: Why does a LIKE query in Access not return any records?
The Access Database Engine (Jet, ACE, whatever) has two ANSI Query Modes which each use different wildcard > characters for LIKE:
ANSI-89 Query Mode uses *
ANSI-92 Query Mode uses %
The LIKE filter should use % instead of * like here:
LIKE '" + identifier + "%'

SQL Error = -804 (C# with firebird database)

I am trying to input data from four text boxes into a Firebird database. Every time I click the button that executes the following code, I get an "SQL Error = -804 Count of read-write columns does not equal count of values."
I'm not sure what this error means. The code I have is:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "User ID=sysdba;Password=masterkey;" +
"Database=localhost:G:\\nael.FDB; " +
"DataSource=localhost;Charset=NONE;";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
FbTransaction addDetailsTransaction =
addDetailsConnection.BeginTransaction();
string SQLCommandText = " INSERT into Invoice_Name Values" +
"('" + textBox1.Text + "',' "
+ textBox2.Text + "',' "
+ int.Parse(textBox3.Text) + "',' "
+ textBox4.Text + "',' "
+ "')";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText,
addDetailsConnection, addDetailsTransaction);
addDetailsCommand.ExecuteNonQuery();
addDetailsTransaction.Commit();
MessageBox.Show(" Details Added");
}
I bet one of your TextBox.Text values has a comma in it... Otherwise: Did you check to see if you are specifying the right amount of columns?
Basically, the SQL engine is complaining that you gave it a list of parameters and it is trying to fill those into the table Invoice_Name, except, it has too many values for the count of columns in that table. Try printing SQLCommandText to the output window (Debug.WriteLine(SQLCommandText)) and see if that is what you expect it to be...
You should also not be doing it this way... check this post here: Inserting into DB with parameters safe from SQL injection?

SQL Update - Not updating multiple rows in a for loop

I have a DataGridView(DGV) linked to a SQlite database. I want to update some info on the DGV. So, I have a context menu that lets me change one column and update the DB as well. I want to have the ability to select multiple rows and edit as well. For ex: if i select five rows and change the type from alarms to errors ; the change is reflected in the DGV and then when i look into the database , the change isnt reflected. Only one row is updated.
My code snippet is below
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
SQLiteTransaction SQLiteTrans = connection.BeginTransaction();
SQLiteCommand cmd = connection.CreateCommand();
MessageBox.Show(r.ToString());
if (r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().Contains("#") == false)
{
r.Cells["typeDataGridViewTextBoxColumn"].Value = r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString() + " # " + max;
}
else
{
r.Cells["typeDataGridViewTextBoxColumn"].Value = r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().Substring(0, r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().IndexOf("#")) + "# " + max;
}
string querytext = "Update LogDatabase set Type = \"" + r.Cells["typeDataGridViewTextBoxColumn"].Value + "\" where HashKey = \"" + r.Cells["hashKeyDataGridViewTextBoxColumn"].Value.ToString() + "\"";
cmd.CommandText = querytext;
cmd.ExecuteNonQuery();
SQLiteTrans.Commit();
}
I dont have too much experience with SQL. So, im not sure if something is wrong with how ive updated the database!
What do i have to edit to make sure all the rows are updated in the DB as well?!
Help appreciated.
Edit: Tried checking the query before its sent.
When i try editing multiple rows in the DGV without sorting the DGV under any column it works and updates all the rows simultaneously... But When I try to sort them based on "Type" and then edit the rows, the same query is passed ! :| (Hash Key doesnt change)
Its like, the one row keeps moving up the list of rows and is always the row r in the for loop.
Edit 2: Its definitely a problem with the rows of the DGV
Everytime I sort the DGV and then try to edit the fields, the queries have hashkey values different from the once that i selected. Its like the row ids are changed completely after one update. It looks like the DGV automatically sorts once one row is updated !
Is there a way to disable this???!
It looks like you weren't increasing max counter.
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
using (SQLiteTransaction SQLiteTrans = connection.BeginTransaction())
{
SQLiteCommand cmd = connection.CreateCommand();
MessageBox.Show(row.ToString());
var txtValue = row.Cells["typeDataGridViewTextBoxColumn"].Value;
if (txtValue.Contains("#"))
{
txtValue = String.Format("{0} # {1}", txtValue, max);
}else
{
txtValue = txtValue.SubString(0, txtValue.IndexOf("#")) + "# " + max.ToString();
}
string querytext = "Update LogDatabase set Type = #type where HashKey = #key";
//Create your SqlParameters here!
cmd.CommandText = querytext;
cmd.ExecuteNonQuery();
SQLiteTrans.Commit();
max++; //You weren't increasing your counter!!
}
}
Your problem is that you are using double quotes in your SQL query to delimit your string values. Replace them for single quotes:
string querytext = "Update LogDatabase set Type = '" +
r.Cells["typeDataGridViewTextBoxColumn"].Value +
"' where HashKey = '" +
r.Cells["hashKeyDataGridViewTextBoxColumn"].Value.ToString() +
"'";
Also, beware of SQL Injection. Your code is not dealing with that.

Using items from List<string> in SQL query

Ok, I have a list that consists of a bunch of values from a sql query, that part works fine. What I want to do is use the items in that list to tell another query what to look for. So, what it is saying is that, it should return all columns from CMMReports where PartNumber is like %listItem1..2...3%, Any advice?
List<string> ImportedParts = GetImportedPartNumbers();
string query = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND PartNumber LIKE %" + ImportedParts + "% ORDER BY CreatedOn DESC;";
Not that I condone this as you should be using parameterized queries. However, this should work:
StringBuilder partNumbers = new StringBuilder();
foreach (string queryValue in ImportedParts)
{
string q = "PartNumber LIKE '%" + queryValue + "%'";
if (string.IsNullOrEmpty(partNumbers.ToString())
{
partNumbers.Append(q);
}
else
{
partNumbers.Append(" OR " + q);
}
}
string query = string.Format("SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') " +
"AND (FilePath NOT LIKE '%js91162%') AND ({0}) " +
"ORDER BY CreatedOn DESC;", partNumbers.ToString());
You might look up the IN clouse for SQL that way you get the answer for the parts that SQL Server can find in the database. Using WHERE x = y for all the items means that if one item can't be found the whole query returns nothing.
I would consider doing this in a stored procedure and passing in your list as an Xml parameter.
See the following article for more info on using Xml parameters in a stored proc:
Passing lists to SQL Server 2005 with XML Parameters - By Jon Galloway
Form there you can easily use your list data inside your stored proc using the Xml syntax and treat it almost as another table of data.
Untested, but you should get the idea:
List<string> ImportedParts = GetImportedPartNumbers();
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND (";
int i = 0;
foreach (string part in ImportedParts) {
cmd.AddParameterWithValue("#param" + i.ToString(), "%" + part + "%");
if (i != 0) cmd.CommandText += " OR"
cmd.CommandText += " PartNumber LIKE #param" + i.ToString();
i++;
}
cmd.CommandText += ") ORDER BY CreatedOn DESC;";
This solution uses a parameterized query instead of just appending strings in the SQL, which is considered a potential security risk.

Categories

Resources