I need to delete certain data from an access database when a button is clicked and it keeps throwing an error relating to the executeNonquery(), I'm really new to this I would appreciate any help, here is my code
private void btnDelete_Click(object sender, EventArgs e)
{
OleDbConnection myDb = new OleDbConnection(connectionString + DBFile);
myDb.Open();
if (ComboBoxSelection.SelectedIndex == 0)
{
OleDbCommand command = new OleDbCommand();
command.Connection = myDb;
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
string query = "DELETE FROM Clients WHERE ClientID = '{int.Parse(txtEdit.text)}'";
command.CommandText = query;
}
command.ExecuteNonQuery();
myDb.Close();
}
else if (ComboBoxSelection.SelectedIndex == 1)
{
OleDbCommand command = new OleDbCommand();
command.Connection = myDb;
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
string query = "DELETE FROM Clients WHERE ClientID = '{txtEdit.text}'";
command.CommandText = query;
}
command.ExecuteNonQuery();
myDb.Close();
}
}
Making a lot of assumptions about what you are trying to do, which is delete from the database every client id in the selected rows. This is a big assumption since you are using the same TextBox in your sample code for each row but I'm guessing this is a work in progress and you were going to get there eventually.
First, commands and connections are disposable resources so you should make sure they are Disposed when you are done with them. A common way to do that is to instantiate them in using blocks as I show below.
Second, you should always use parameterized queries, never concatenate strings together. I don't know if ClientID is a string or a number, you appear to use it both ways, but if someone typed ' OR 1=1; -- into the text box while the combobox was on index 1 then you could end up with everything deleted.
Lastly, you have a lot of duplication. Based on my assumptions, you can clean up your code to this:
private void btnDelete_Click(object sender, EventArgs e)
{
string query = "DELETE FROM Clients WHERE ClientID = #ClientID";
using (OleDbConnection myDb = new OleDbConnection(connectionString + DBFile))
using (OleDbCommand command = myDb.CreateCommand())
{
int clientid = 0;
command.CommandText = query;
OleDbParameter parClientID = new OleDbParameter("#ClientID", OleDbType.Integer);
command.Parameters.Add(parClientID);
myDb.Open();
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
//Assume your client id is in a cell of the row? Zero for first, One for second, etc.
if (int.TryParse(myRow.Cells[0].ToString(), out clientid))
{
parClientID.Value = clientid;
command.ExecuteNonQuery();
}
}
}
}
Related
I want to update an Oracle Database table after querying the table and applying an encryption function to the retrieved data from some fields. However, my code (below) does not work correctly:
private void button2_Click(object sender, EventArgs e)
{
using (OracleConnection conn = new OracleConnection(oradb))
conn.Open();
OracleCommand select = new OracleCommand("select empno,FNAME,LNAME from employee", conn);
OracleDataReader reader = select.ExecuteReader();
Int64 vempno = 0;
String fnameValue = "";
String lnameValue = "";
String afterConcatfname = "";
String afterConcatlname = "";
if (reader.HasRows)
{
while (reader.Read())
{
vempno = reader.GetInt64(0);
fnameValue = reader.GetString(1);
lnameValue = reader.GetString(2);
REA rea = new REA();
afterConcatfname = rea.Encrypt(fnameValue, rea.GenerateKey());
afterConcatlname = rea.Encrypt(lnameValue, rea.GenerateKey());
}
reader.Close();
}
OracleCommand update = new OracleCommand("update employee set fname =:fname, lname =:lname where empno =:empno", conn);
OracleParameter fname = new OracleParameter("fname", afterConcatfname);
OracleParameter lname = new OracleParameter("lname", afterConcatlname);
OracleParameter empno = new OracleParameter("empno", vempno);
update.Parameters.Add(fname);
update.Parameters.Add(lname);
update.Parameters.Add(empno);
update.ExecuteNonQuery();
}
I don't receive any error but the program encrypts only the last record with all the encrypted values. I want to encrypt every row.
"I dident receive any error ,but the program encrypts only the last record by all the encrypted values "
That's the logic of your code. Basically, what you are doing is this:
loop
read one row
encrypt one row
end loop
update one row
" I want to encrypt row by row "
So you need to move the update logic into the loop, so that it is executed for each row.
A better solution would be to replace row-by-row processing with a set operation, but that's a different question.
I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you
I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.
In my code I created a table and exported a CSV file to it. in another section of my code the comboBox is populated with the table names from my database. This is shown below:
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
What am trying to achieve is to refresh the comboBox as to reflect the newly added table which was executed through the above function. What came to mind first was to create a button and rewrite the above function like this:
private void button1_Click_1(object sender, EventArgs e)
{
//this is where I would just rewrite the contents of the above function
}
As you guessed, it works but the values are duplicated. How do I refresh the comboBox without duplicating the existing info?
As I mentioned at comments you can clear items before recall method with,
combobox.Items.Clear();
Or you can add If statement at while loop like this,
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
if (!comboBox1.Items.Contains(dr2[col].ToString()))
{
comboBox1.Items.Add(dr2[col].ToString());
}
}
So you don't need to clear items every recall.
Hope helps,
I'm trying to delete all the rows of a particular Aperture (of Bussiness) whenever the user clicks the button (which is a Save button), so to then insert the data to save. The code is the following:
private void button2_Click(object sender, EventArgs e)
{
SQLiteCommand cmdDel = new SQLiteCommand();
cmdDel = SQLconnect.CreateCommand();
cmdDel.CommandText = "DELETE FROM GridTable WHERE Aperturas=#combo";
cmdDel.Parameters.AddWithValue("#combo", combo1.Text);
cmdDel.ExecuteNonQuery();
DataTable dt = (DataTable)grid1.DataSource;
string sql = "INSERT INTO GridTable (Aperturas, Ventas, Proveedores, EAE, EAM) VALUES (#aperturas,#ventas,#proveedores,#eae,#eam)";
foreach (DataRow r in dt.Rows)
{
SQLiteCommand cmd = new SQLiteCommand();
cmd = SQLconnect.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#aperturas", combo1.Text);
cmd.Parameters.AddWithValue("#ventas", r["Ventas"]);
cmd.Parameters.AddWithValue("#proveedores", r["Proveedores"]);
cmd.Parameters.AddWithValue("#eae", r["Egreso Axel Efectivo"]);
cmd.Parameters.AddWithValue("#eam", r["Egreso Axel Mercaderia"]);
cmd.ExecuteNonQuery();
}
}
the problem is that the delete function does not seem to do anything, when i load the data back it appears duplicated, as if it was inserted for a second time (which it was, but not to end up showing like that)
Thank you in advance.
Can anybody help me with the issue I'm seeing? For some reason when I run my page, I get my drop down lists to populate the data, however the first item in my database, per each SQL query, doesn't get populated.
For example, my database table is:
Category
1 Books
2 Clothing
3 Toys
4 Household Items
my first query -
SELECT Category FROM ProductCategories
my drop down list gets populated with
Clothing
Toys
Household Items
I have 2 other drop down lists I'm populating and those are doing the same thing. Once I get this figured out, I'll try to figure out the other problem I'm having with inserting the data in the database.
Thank you!
public partial class InsertItems : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection;
SqlCommand populateList;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
connection = new SqlConnection(connectionString);
populateList = new SqlCommand("USE LakerBids SELECT Category FROM ProductCategories;" +
"USE LakerBids SELECT SubCategory FROM ProductSubCategories;" +
"USE LakerBids SELECT LName FROM Users", connection);
if (!IsPostBack)
{
try
{
connection.Open();
reader = populateList.ExecuteReader();
while (reader.Read())
{
pcategory.DataSource = reader;
pcategory.DataValueField = "Category";
pcategory.DataBind();
}
reader.NextResult();
while (reader.Read())
{
psubcategory.DataSource = reader;
psubcategory.DataValueField = "SubCategory";
psubcategory.DataBind();
}
reader.NextResult();
while (reader.Read())
{
user.DataSource = reader;
user.DataValueField = "LName";
user.DataBind();
}
reader.Close();
}
finally
{
connection.Close();
}
}
}
protected void AddItem(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection connection;
SqlCommand insertData;
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
connection = new SqlConnection(connectionString);
insertData = new SqlCommand("INSERT INTO Products (ProductName, ProductDesc, CategoryID, SubCatID, StatusID, UserID, ReservePrice, AuctionLength, BidID)" +
"VALUES (#ProductName, #ProductDesc, #CategoryID, #SubCatID, 1, #UserID, #ReservePrice, #AuctionLength, NULL)", connection);
insertData.Parameters.Add("#ProductName", System.Data.SqlDbType.NVarChar, 50);
insertData.Parameters["#ProductName"].Value = pname.Text;
insertData.Parameters.Add("#ProductDesc", System.Data.SqlDbType.NVarChar, 200);
insertData.Parameters["#ProductDesc"].Value = pdesc.Text;
insertData.Parameters.Add("#CategoryID", System.Data.SqlDbType.Int);
insertData.Parameters["#CategoryID"].Value = pcategory.SelectedIndex;
insertData.Parameters.Add("#SubCatID", System.Data.SqlDbType.Int);
insertData.Parameters["#SubCatID"].Value = psubcategory.SelectedIndex;
insertData.Parameters.Add("#UserID", System.Data.SqlDbType.Int);
insertData.Parameters["#UserID"].Value = user.SelectedIndex + 2;
insertData.Parameters.Add("#ReservePrice", System.Data.SqlDbType.Money);
insertData.Parameters["#ReservePrice"].Value = Convert.ToDecimal(reserveprice.Text);
insertData.Parameters.Add("#AuctionLength", System.Data.SqlDbType.Int);
insertData.Parameters["#AuctionLength"].Value = Convert.ToInt32(auctionlength.Text);
try
{
connection.Open();
insertData.ExecuteNonQuery();
Response.Redirect("Categories.aspx");
}
catch (Exception error)
{
dberror.Text = error.ToString();
}
finally
{
connection.Close();
}
}
}
}
You need to either use a DataSet or populate business entities within a collection and then bind to the collection.
List<Category> cats = new List<Category>();
while (reader.Read())
{
Category cat = new Category();
// fill properties from DataReader
cats.Add(cat);
}
pcategory.DataSource = cats;
pcategory.DataValueField = "Category";
pcategory.DataBind();
Sab0tr0n, I suspect one of two things are happening.
1) If you are saying the first item does not appear AFTER you do some kind of "Add Category" action, then it might be that the dropdown is populated BEFORE the insert completes. Meaning, you need to requery after allowing the insert to be committed to the database.
OR
2) Put a breakpoint on this line:
string connectionString = ConfigurationManager.ConnectionStrings["LakerBids"].ConnectionString;
Then confirm the connectionString is to the correct database. I've seen old config files that point to test or staging databases cause this kind of confusion.
Good luck. If these aren't the answer, maybe simplify your example to us or elaborate on exactly what you do with your application and when you see the problem.
The "reader.read()" statement in each block is actually reading the first row of data, so when you set the DataSource, the first row has already been read. Try taking it out
You should use "while (reader.Read())" if you want to iterate over each result, not bind the resulset in one step.
That being said, the comments about using a Dataset, seperating logic, etc., are valid