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.
Related
I have a Textbox with which I want to be able to Search and Insert data into Table. Insert works fine with one exception: When I try to Insert data that isn't already in DB(it's searching while I'm typing) it gives me:
"Exception User-Unhandled System.NullReferenceException: 'Object
reference not set to an instance of an object.'
System.Windows.Forms.DataGridView.CurrentRow.get returned null.
I think I'm missing something in the Search code.
//UPDATE: All of the code.// This is my Insert and Search code:
namespace UDDKT
{
public partial class FrmGlavna : Form
{
DataSet ds = new DataSet();
SqlDataAdapter DaDavaoci = new SqlDataAdapter();
SqlDataAdapter DaAkcije = new SqlDataAdapter();
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
public FrmGlavna()
{
InitializeComponent();
}
//Popunjava DataGridViews sa podacima iz baze
private void FrmGlavna_Load(object sender, EventArgs e)
{
SqlCommand SlctDavaoci = new SqlCommand("SELECT * FROM Davaoci ORDER BY DavaocID DESC", cs);
DaDavaoci.SelectCommand = SlctDavaoci;
DaDavaoci.Fill(ds, "TblDavaoci");
SqlCommand SlctAkcije = new SqlCommand("SELECT * FROM AkcijaDDK", cs);
DaAkcije.SelectCommand = SlctAkcije;
DaAkcije.Fill(ds, "TblAkcije");
DgDavaoci.DataSource = ds.Tables["TblDavaoci"];
}
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
//Osvježava DataGridView nakon unosa/izmjene/brisanja podataka u bazu
private void RefreshTable()
{
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
String query = "SELECT * FROM Davaoci ORDER BY DavaocID DESC";
SqlCommand cmd = new SqlCommand(query, cs);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DgDavaoci.DataSource = dt;
}
//Čisti TextBox nakon upisa/izmjene/brisanja podataka u bazu
public void ClearTxtBx()
{
TxtIme.Clear();
TxtPrezime.Clear();
TxtTezina.Clear();
TxtAdresa.Clear();
TxtBrojTel.Clear();
TxtBrojLK.Clear();
}
//Upis podataka u Tabelu Davaoci
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(query, cs))
{
command.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
command.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
command.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
command.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = TxtDatumRodjenja.Text;
command.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
command.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
command.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
command.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
command.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
command.ExecuteNonQuery();
cs.Close();
RefreshTable();
ClearTxtBx();
}
}
//Pretraga postojećih Davalaca
private void TxtIme_TextChanged(object sender, EventArgs e)
{
(DgDavaoci.DataSource as DataTable).DefaultView.RowFilter = string.Format("Ime LIKE '{0}%'", TxtIme.Text);
}
}
}
}
Here is the MockUp of the Form before I begin to type/search/insert Data that isn't already in the Table (First Textbox*).
And after I start typing Name(Име) that starts with an "A" (name that isn't already in the Table).
I want to Search DB for that Column, but if there aren't any existing names, I want to be able to continue typing (without interuption) so that I can Insert new data into table.
DgDavaoci.CurrentRow in your DgDavaoci_SelectionChanged method is null, so attempting to access DgDavaoci.CurrentRow.Cells["DavaocID"] throws the NullReferenceException. The reason, best I can tell, is as follows:
You begin to type a value into your text box, a value that happens not to be found in the data set. As you type, you cause the TxtIme_TextChanged method to execute. It filters according to your search, and since the value is not found, it filters out every row in the set. Here's the important part: whenever the data set is filtered, it has the possibility of causing DgDavaoci_SelectionChanged to execute. Since the selection changed from the first row to no row at all (since there are no filtered rows to display), this method does execute. Now, when the method attempts to access the current row, there is no current row, and so we get a null here. Attempting to access a field of null throws the exception you're getting.
How can you fix this behavior? A simple null-check in DgDavaoci_SelectionChanged should do the trick. It looks to me like you can simply return from that method if(DgDavaoci.CurrentRow == null), or you can code in additional behavior. Just perform a check so that you don't reference the null object.
Probably the filter inside TxtIme_TextChanged is causing the DataGridView's SelectionChanged event to fire and the code is entering DgDavaoci_SelectionChanged. The exception indicates that DgDavaoci.CurrentRow is null, so you'll need to handle the case where DgDavaoci.CurrentRow is null in DgDavaoci_SelectionChanged.
A simple way to deal with this would be to just check DgDavaoci.CurrentRow is null and return from the function if that evaluates to true.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
It looks like you might have a second DataGridView (DgAkcije) that is designed to show the details of the currently selected row in DgDavaoci. So, another approach might be to just clear DgAkcije if DgDavaoci.CurrentRow is null.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
DgAkcije.DataSource = null; //I'm not 100% sure this will work, I haven't tested it.
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
Ultimately, however, you'll have to decide what you want to happen when DgDavaoci_SelectionChanged is called but DgDavaoci.CurrentRow is null.
Solution if anyone else is interested:
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow != null)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
}
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();
}
}
}
}
With my program I have a datatable that gets populated with records fetched from a database. This is displayed in a datagrid view and when a cell is clicked it loads all the values into textboxes. When a save button is clicked it will then save the textbox values back into the datatable. However how can I send this datatable back to the database and have it update the records?
Here is my code to load the records:
indexRow = e.RowIndex;
DataGridViewRow row = dgv_ReturnSearch.Rows[indexRow];
tb_editFirstName.Text = row.Cells[1].Value.ToString();
tb_editLastName.Text = row.Cells[2].Value.ToString();
tb_editAge.Text = row.Cells[3].Value.ToString();
tb_editPostCode.Text = row.Cells[4].Value.ToString();
tb_editMobNum.Text = row.Cells[5].Value.ToString();
tb_editEmail.Text = row.Cells[6].Value.ToString();
tb_editAllergies.Text = row.Cells[7].Value.ToString();
tb_editDOB.Text = row.Cells[8].Value.ToString();
tb_editGender.Text = row.Cells[9].Value.ToString();
Here is my code to save them
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
newDataRow.Cells[1].Value = tb_editFirstName.Text;
newDataRow.Cells[2].Value = tb_editLastName.Text;
newDataRow.Cells[3].Value = tb_editAge.Text;
newDataRow.Cells[4].Value = tb_editPostCode.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
However this doesn't actually update the database, only the local datatable. When it is loaded again all the changes revert.
Thanks
To load a gridview with data from the database you'll need to use DataTable and DataAdapter then bind the grid. it should look something like this:
private void CustomersBindGrid()
{
using (SqlConnection con = new SqlConnection(mycon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM Customers";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
con.Close();
}
}
Try updating the database directly:
private void SaveEdits_Click()
{
using (SqlConnection con = new SqlConnection(mycon))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE Customers set firstname= #FN , lastname= #LN , age = #AG , postcode= #PC where CustomerID = #CustID";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#CustID", cid);
cmd.Parameters.AddWithValue("#FN", tb_editFirstName.Text);
cmd.Parameters.AddWithValue("#LN", tb_editLastName.Text);
cmd.Parameters.AddWithValue("#AG", tb_editAge.Text);
cmd.Parameters.AddWithValue("#PC", tb_editPostCode.Text);
cmd.ExecuteNonQuery();
}
}
CustomersBindGrid();
MessageBox.show("Information Updated!");
}
}
You need to edit this update command to your columns in the database and get a way to read the customer id so the condition actually work and update the database.
In your posting, you don't write, how your client is developed...
Normally, this would be done with a SQL update command.
Therefore (in the Microsoft universe) the SqlClient (System.Data.SqlClient Namespace) can be used.
As soon as the user press the save button, you overtake the relevant textbox.text values in variables, change datatypes if necessary, generate an SQL update string to update the data on your SQL server.
Example SQL update string:
Update TableName set ColumnName1Text = 'some text', ColumName2Integer = 12, ColumnName.... = ... where ColumnNameKey = KeyToDatatable
Then you submit the SQL command (SQL update string) to the SQL server via SqlClient (SqlCommand).
But therefore you need a unique key for the where clause (in the example KeyToDatatable) so that only the row with the key is updated.
The key normally is queried from the DataTable (with the other fields) to show the data (in your grid) and then taken over to the update command (can be "hided" from the user, that don't has to know the key).
Well I managed to fix it by doing:
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
dt.Rows[indexRow]["first_name"] = tb_editFirstName.Text;
dt.Rows[indexRow]["last_name"] = tb_editLastName.Text;
dt.Rows[indexRow]["age"] = tb_editAge.Text;
dt.Rows[indexRow]["postcode"] = tb_editPostCode.Text;
dt.Rows[indexRow]["mobile_num"] = tb_editMobNum.Text;
dt.Rows[indexRow]["email"] = tb_editEmail.Text;
dt.Rows[indexRow]["allergies"] = tb_editAllergies.Text;
dt.Rows[indexRow]["DOB"] = tb_editDOB.Text;
dt.Rows[indexRow]["gender"] = tb_editGender.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
Instead of what I was doing before, now it works perfectly and any changes are saved back to the database.
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 have a grid view. If I click the add button, an empty row is created. There is more than one empty row in the grid view. Now if I click the delete button on the selected row, all the empty rows are deleted. I want to delete the selected empty row only.
thank you..please help ..
delete code is here...
protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");
conn.Open();
string cmdstr = "delete from EmployeeDetails where empid=#empid";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", lblEmpID.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
add row code here.........
in add row i want alert message if the name textbox is empty
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
Can you change the "empid" column to be Identity? This is done from SQL management studio and will make your column to be unique and will auto increment the values in it. After that you will remove it from the Add method and the SQL will take care of it. This will fix your problem.
In SQL you must go the the EmployeeDetails table. Choose design from your options and then go the to empid column. On it you can open Column Properties and expand the "Identity Specifications". Then change "(Is Idetity)" to "Yes" and save the table. See the screenshot below:
Then your Add code should look like that:
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
if(string.IsNullOrEmpty(txtAddName.Text))
{
MessageBox.Show("Name is empty"); // or some logging, you decide
}
else
{
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(name,designation,city,country) values(#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
}
also try this one also,
gvEmployeeDetails.DeleteRow(Row name/index);
try this code:
gvEmployeeDetails.AllowUserToAddRows = false;
It will Automatically delete Empty row.