C# How to deleted multiple checked items from the CheckedListBox? - c#

i want to delete one or more selected items in checkedlistbox. But i dont know how i must to do that. Pls help
here my codes;
private void button2_Click(object sender, EventArgs e)
{
checkedListBox1.Items[checkedListBox1.SelectedIndex].ToString();
SqlCommand del = new SqlCommand("DELETE FROM TABLE1 WHERE personID='" +
personID[checkedListBox1.SelectedIndex] + "' ", con);
con.Open();
for (int i = 0; i < checkedListBox1.Items.Count - 1; i++)
{
if(checkedListBox1.CheckedItems[i]) //this line does not work
{
del.ExecuteNonQuery();
}
}
con.Close();
}

You should use a parameter for security reason.
Next you can set it in the loop with the desired id.
con.Open();
var command = new SqlCommand("DELETE FROM TABLE1 WHERE personID=? ", con);
var param = del.Parameters.Add("#ID", SqlDbType.Int /* or any relevant type */);
foreach ( var item in checkedListBox1.SelectedItems )
{
param.Value = ((TheTypeOfTheItems)item).NameOfTheID;
command.ExecuteNonQuery();
}
con.Close();
Perhaps you can construct only one query by adding some OR to the WHERE clause and execute it one time after the loop.
if ( checkedListBox1.SelectedItems.Count > 0 )
{
con.Open();
var command = new SqlCommand("DELETE FROM TABLE1 WHERE ", con);
var id = ( (TheTypeOfTheItems)checkedListBox1.SelectedItems[index] ).NameOfTheID;
command.CommandText += "personID =? ";
command.Parameters.Add("#ID" + index, SqlDbType.Int).Value = id;
if ( checkedListBox1.SelectedItems.Count > 1 )
for ( int index = 1; index < checkedListBox1.SelectedItems.Count; index++ )
{
command.CommandText += "OR ";
var id = ( (TheTypeOfTheItems)checkedListBox1.SelectedItems[index] ).NameOfTheID;
command.CommandText += "personID =? ";
command.Parameters.Add("#ID" + index, SqlDbType.Int).Value = id;
}
command.ExecuteNonQuery();
con.Close();
}
Note: I can't test the code and I used params with odbc and not sql server.

Related

Replacing if (Convert.ToString(rdr["Data"]) != bItems)

I want to replace if (Convert.ToString(rdr["Data"]) != bItems) with something that would check if data already exist in my database or not to make process faster as going in that loop taking too much time for bigger database. Plz HELP!
for (int p = 0; p < 256; p++) {
bItems += "P" + buffer[p];
}
using (SQLiteConnection con = new SQLiteConnection(databaseObject.myConnection)) {
con.Open();
SQLiteCommand cmd = new SQLiteCommand("select ID, Data from B where Data like 'P%'", con);
var rdr = cmd.ExecuteReader();
while (rdr.Read()) {
if (Convert.ToString(rdr["Data"]) != bItems) {
SQLiteCommand cmd1 = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT ID, Data FROM B WHERE Data = #Data)", con);
cmd1.Parameters.AddWithValue("#Data", bItems);
cmd1.ExecuteNonQuery();
}
else (Convert.ToString(rdr["Data"]) == bItems) {
sItems = "B" + Convert.ToString(rdr["ID"]);
rdr.Close();
break;
}
}
}
bItems = "";
Console.WriteLine(sItems);
}
instead of reading each row and check the data against bItems. You may need to either query the table to see if there is any record matches bItems, if not then insert it. Or, you can simply insert the data if not exists (which what you did in the first condition.
To simplify your work, you can do this :
// insert the new item if not exists in the table
// returns the item Id
private int InsertDataIfNotExists(string bItems)
{
using (SQLiteConnection connection = new SQLiteConnection(databaseObject.myConnection))
using(SQLiteCommand command = new SQLiteCommand("INSERT INTO B ('Data') SELECT #Data WHERE NOT EXISTS (SELECT 1 FROM B WHERE Data = #Data);", con))
{
connection.Open();
command.Parameters.AddWithValue("#Data", bItems);
// insert data if not exists
command.ExecuteNonQuery();
// get the data's Id
cmd.CommandText = "SELECT ID FROM B WHERE Data = #Data LIMIT 1;";
cmd.Parameters.AddWithValue("#Data", bItems);
var result = cmd.ExecuteScalar()?.ToString();
return int.TryParse(result, out int id) && id > 0 ? id : -1;
}
}
with the above, you only insert the data if not exists, and then return the id.
usage :
var insertResultId = InsertDataIfNotExists(bItems);
if(insertResultId == -1)
{
// handle exceptions
}
else
{
Console.WriteLine(insertResultId);
}

Check if value in database table Asp.net C#

I have a stored procedure that would count the number of times a value is in a database. However in the code behind for loop when it reaches
(int)command.ExecuteScalar(); the loop stops and asks to supply parameter for #invoice2.
Stored Procedure:
select count(*) as CountInvoice where invoice1=#invoice1 or #invoice2=#invoice`2
Code Behind:
using (SqlCommand command = new SqlCommand("sp_Count", conn))
{
foreach (TextBox textBox in placehldr1.Controls.OfType<TextBox>())
{
count += 1;
command.CommandType = CommandType.StoredProcedure;
string invoice = textBox.Text.TrimEnd();
string parameter = string.Format("#invoice{0}", count);
command.Parameters.AddWithValue(parameter, invoice);
int invoiceCount = (int)command.ExecuteScalar();
if (invoiceCount > 0)
{
lblError.Text = "Invoice number already exist";
return;
}
command.Parameters.Clear();
}
Would something like this work better as it factors in the two parameters.
select count(*) as CountInvoice where invoice1=#invoice1 or invoice2=#invoice2
using (SqlCommand command = new SqlCommand("sp_Count", conn))
{
foreach (TextBox textBox in placehldr1.Controls.OfType<TextBox>())
{
count1 += 1;
count2 += 1;
command.CommandType = CommandType.StoredProcedure;
string invoice = textBox.Text.TrimEnd();
string parameter1 = string.Format("#invoice1", count1);
string parameter2 = string.Format("#invoice2", count2);
command.Parameters.AddWithValue(parameter, invoice);
int invoiceCount = (int)command.ExecuteScalar();
if (invoiceCount > 0)
{
lblError.Text = "Invoice number already exist";
return;
}
command.Parameters.Clear();
}

Insert all data of a datagridview to database C#

I have a datagridview which is created by various action and user's manipulation of data. I want to insert all the data of the gridview to the database at once, I know I could try a code similar to this:
private void btnSaveProducts_Click(object sender, EventArgs e)
{
SqlConnection connection = DBConnectivity.getConnection();
if (connection != null)
{
try
{
for (int i = 0; i < dGvProducts.Rows.Count; i++)
{
string query = "INSERT INTO product (productName) " + "VALUES (#productName)";
SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
int result = command.ExecuteNonQuery();
Console.WriteLine(result + "");
}
// string query = "Insert into units(name,packing)values('" + txtNameUnit.Text + "' , '" + txtPackingUnit.Text + "')";
// SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
// int result = command.ExecuteNonQuery();
// Console.WriteLine(result + "");
}
catch (Exception ex)
{
}
finally
{
connection.Close();
}
}
}
As is, the code tries to execute a parameterized query but never assigns a value to the parameter. Even if you do, you never extract the cell values.
The code should look like this:
var query = "INSERT INTO product (productName) VALUES (#productName)";
using var(connection = DBConnectivity.getConnection())
using(var command = new SqlCommand(query, connection))
{
var productParam=command.Parameters.Add("#productName",SqlDbType.NVarChar,50);
connection.Open();
for (int i = 0; i < dGvProducts.Rows.Count; i++)
{
var productName=dGvProducts.Rows[i].Cells[somecolumn].Value;
productParam.Value=productName;
int result = command.ExecuteNonQuery();
Console.WriteLine(result);
}
}

Minus data from the program to the database

How do i minus data from the program to the database?
I have quantity and description in my database.
The quantity will be 100, and the description of it will be A.
When i type in my program like this (after run the program):
The quantity is 50. and the description of it is A.
The database:
The quantity will be 50 (because minus with the database and my program "100 - 50 = 50", and the description still remains same as A.
How do i do that?
Thanks in advance!
Edit:
I already did like this:
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Value = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0)
{
if (textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
decimal newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
}
}
But when i run the program, the quantity loaded exactly the same like in the database, but it can't change, when i type quantity is 50, the program will automatically return to 100 (which is same exactly the quantity in the database)
Why is it like that?
Note: for textbox quantity, i use the Numeric Up Down.
Edit: The full code is on below:
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Value = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0)
{
if (textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
decimal newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
}
}
index += 1;
}
dReader.Close();
conn.Close();
}
}
private void UpdatePrice()
{
int totalPrice = 0;
int quantity = 0;
int price = 0;
for (int i = 0; i < 17; i++)
{
if (textBoxQuantityContainer[i].Value > 0)
{
quantity = (int)textBoxQuantityContainer[i].Value;
price = Convert.ToInt32(textBoxSubTotalContainer[i].Text);
textBoxTotalContainer[i].Text = (quantity * price).ToString();
}
else
{
textBoxSubTotalContainer[i].Text = "";
textBoxTotalContainer[i].Text = "";
}
}
for (int i = 0; i < 17; i++)
{
if (textBoxTotalContainer[i].TextLength != 0)
{
totalPrice += Convert.ToInt32(textBoxTotalContainer[i].Text);
}
}
textBoxAllTotalContainer.Text = totalPrice.ToString("n2");
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
}
}
Here is the screenshot:
"Code" displayed in the screenshot above is refer to the database, and also the "Quantity", whenever i type the code that already have in the database, the remaining box are filled up. But, when i change the "Quantity" from 100 to 50, it is automatically like refresh the program to back to 100 again.
cmd = new oledbcommand("select qty from tablename where pid=103");
qtyval = convert.ToInt32(cmd.ExecuteScalar());
if (qtyval != 0 )
{
if (qtyval >= convert.toint32(txtqty.text))
{
newval = qtyval - convert.ToInt32(txtqty.text);
cmd = new oledbcommand("update tablename set qty="+newval+" where pid=103");
}
}
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (");
[This can't be your actual code because it is missing a closing quote and bracket. Please always just copy and paste your actual code.]
WHERE [Code] IN (")
You are attempting to update where the Code is an empty string? It is far more likely to be NULL, so this is one reason why it won't update. However, you haven't executed this cmd, so it won't change anything.
[Do you really intend to update ALL records which don't have a Code ?]
You should also print-out cmd and attempt to execute it from within Access as part of your debugging steps.
Lastly, why are you quoting the Quantity with apostrophes? Presumably, it is a numeric field.

replace method mechanism

i face the following problem::
i wanna to escape the following character ' single quote:
it works when making this test through :the built in method Replace("'","''");
as this code below :(just a test) it works
protected void btn_insert_Click(object sender, EventArgs e)
{
lbl.Text = string.Empty;
SqlConnection mycon = new SqlConnection(Constr);`
SqlCommand mycommand = new SqlCommand("INSERT INTO details VALUES('" + txt.Text.Replace("'", "''") + "','" + txt.Text.Replace("'", "''")+ "')", mycon);
mycon.Open();
int affectedRows = 0;
affectedRows = mycommand.ExecuteNonQuery();
mycon.Close();
}
but i wanna to generalize my solution to work all over the application through my Insert method in the data access layer:
public static int InsertEntity(string tblName, Dictionary<string, string> dtParams)
{
int Result = -1;
DBConnection DAL_Helper = new DBConnection("");
string[] field_names = new string[dtParams.Count];
dtParams.Keys.CopyTo(field_names, 0);
string[] field_values = new string[dtParams.Count];
dtParams.Values.CopyTo(field_values, 0);
for (int i = 0; i < field_values.Length; i++)
{
field_values[i].Replace("'", "''");
}
string insertCmd = "INSERT INTO " + tblName + " (" + string.Join(",", field_names) + ") values ('" + string.Join("','", field_values) + "')";
Result = DAL_Helper.Execute_NonQuery(insertCmd);
return Result;
}
this not escaping the ' single quote charecter,although i use Replace("'","''");
what is the problem ,,how to fix this problem?
I strongly recommend you use Command Parameters using SqlCommand.Parameters collection instead of your approach.
Problem is here :
for (int i = 0; i < field_values.Length; i++)
{
field_values[i].Replace("'", "''");
}
Replace it with :
for (int i = 0; i < field_values.Length; i++)
{
field_values[i] = field_values[i].Replace("'", "''");
}
Building on decyclone's answer. CommandParameters are the way to go here, you are just re-inventing it with your own code.
I have found a very nice clear example here for supplying params to a SQL statement.
http://dotnetperls.com/sqlparameter
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
string dogName = "Mc'Dougal";
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
}

Categories

Resources