How to delete multiple rows in gridview then update data in database? - c#

I want to delete some selected rows of data contained in grid view by pressing delete button, how to do it ?
This code works if data is not bound to the database:
foreach (DataGridViewRow row in DGV1.SelectedRows)
{
DGV1.Rows.RemoveAt(row.Index);
}
And this is my code to clear data in gridview based on value in Z_1_lblSupplier_Name.Text.
string sqlquery = "DELETE FROM tb_supplier_list WHERE Supplier_name='" + Z_1_lblSupplier_Name.Text + "'";
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
MySqlDataReader sdr;
mysqlconn.Open();
sdr = sqlcmd.ExecuteReader();
mysqlconn.Close();
I don't know how to combine them, I want users to be able to select multiple rows of data in grid view which they want to delete, then simultaneously data in database is also deleted.

Related

C# mysql view only specific columns in data grid view

Short and probably easy question, I don't want to view in dataGridView columnID and few more columns as there is no use of viewing that info.
I have a clear code, the connection is open, the data loads fine and the comment code (btw most common solution in google) gives empty table with all columns (no rows).
I tried so many things that I can't even list them there :(
Any ideas?
DataTable SqlDataTable = new DataTable();
MySqlDataReader reader;
MySqlCommand sqlCommand = new MySqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM table_name";
reader = sqlCommand.ExecuteReader();
//while (reader.Read())
//{
// string columnID = reader["columnID"].ToString();
//}
SqlDataTable.Load(reader);
reader.Close();
sqlConnection.Close();
DataGridView = SqlDataTable;
First when U want view data in DataGridView U should set the data source of it's like
DataGridView.DataSource = yourDataTable
Second, if U want to hide DataGridView column, U most know the index of the column or the name and then you can use this code
I assume the first column is ID
So
By Index
DataGridView.Columns[0].Visible = false;
By Name
DataGridView.Columns["ID"].Visible = false;

How to delete record from table which is not binded to gridview using rowdeleting event?

I have one webpage developed in C# asp.net. Here, I have gridview which is binded to my table1.
UserDetails columns are id, userID, user name
I have another DashbaordData having columns - data1, data2, and createdby.
here input data of createdby column from DashbardData and userID from userDetails are the same.
I want to delete record from DashbardData , from the row deleting event of gridview (which is binded to userDetails) on the where condition of DashbardData .createdby=userDetails.userID.
protected void GridView1_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label id = (Label)row.FindControl("lblRecordID");
Label userID = (Label)row.FindControl("lbluserID");
OleDbConnection con = new OleDbConnection(conDB);
OleDbCommand cmd1 = new OleDbCommand();
cmd1.CommandText = "delete* from DashboardData where Createdby =" + userID.Text + "";
cmd1.Connection = con;
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
Here in code, i am getting the userID value from userdetails table which is binded to gridview, and passing that userID to delete query to delete record from Dashbaordata table.
In debug i see that query is correct, it is picking up the correct value but when it execute cmd1.ExecuteNonQuery(); nothing happnes. it goes to catch section and give error as parameters not found.
I have doubt whether we can do like this- deleting another table record using row deleting event of some different table gridview ?
could you please help me how I can do it.

Alternative Ways In Adding New Rows in Datasource Data Grid View

I'm creating a project in C# windows form. What I'm trying to do is add new rows in the datasource data grid view. But the problem is, the error says that adding new rows can't add programmatically in the datasource data grid.
Here's my method in fetching the data and transfer it in the data grid view.
public DataTable GetData(ClassName classVar){
SqlCommand cmd = new SqlCommand();
cmd.Connection = ...; // My connection string
cmd.CommandType = CommandType.Text;
cmd.CommandText = ...; // My Query
DataTable table = new DataTable();
table = ...ExeReader(cmd);
return table;
}
The Codes inside my form
DataTable getDataTable;
getDataTable = ClassQuery.GetData(classVar);
dgv_details.DataSource = getDataTable;
And this is my add button
dgv_details.Rows.Add(txtBox1.Text,txtBox2.Text);
What are the alternative ways in adding data inside the datasourced datagridview?
Thanks in advance.
Try the below code. First add row to datatable and then bind that table to datagridview.
DataRow dr = datatable1.NewRow();
dr[0] = "HAI"; // add data in first column of row
datatable1.Rows.InsertAt(dr, 0); // insert new row at position zero
datatable1.Rows.Add(dr); // addnew row at last

Deleting selected row of datagrid from database?

I have a DataGrid and a delete button in my form. When I click the delete button, it should delete the selected row of datagrid from my Access database. but it is just removed from the datagrid not the database. when I load the form again the deleted rows are still there. Here is the code of my delete button:
con.Open();
OleDbCommand comnd = new OleDbCommand();
comnd.Connection = con;
string q = "delete from customers";
comnd.CommandText = q;
comnd.ExecuteNonQuery();
MessageBox.Show("delete");
So you try to delete a single row from your database, with the following query:
delete from customers
The problem is that this query does not specify which row should be affected by it. You have to understand that your DataGrid here is not the same as your DataBase.
In order to delete a specific row from the database you should also specify which row it is. For example you could tell it to delete a row with a certain id:
delete from customers where id = 7
The above query will delte all rows with the id 7. But this is only one possible approach.
For this you would actually need id's in your table. The following code is from a MSDN-source. It deletes entries with a specific id which comes from the datagrid:
int ID = (int) datagrid.DataKeys[(int) e.Item.ItemIndex];
string sql = "DELETE FROM PetTable WHERE ID=" + ID;
ExecuteNonQuery(sql);
For further information you should read this.
you need to iterate through the selected row deleting all of them something like the below
foreach (DataGridViewRow row in datagrid1.SelectedRows)
{
//get key
int rowId = Convert.ToInt32(row.Cells[indexWhereIdStored].Value);
// your delete logic
}
If you need to delete only one selected row assuming that the first column is the key
if (datagrid1.SelectedRows.Count > 0)
{
int selectedIndex = datagrid1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = int.Parse(datagrid1[0, selectedIndex].Value.ToString());
// you can create a parameter for the #RowID
string sql = "DELETE FROM YourTable WHERE RowID = #RowID";
// your code for deleting it from the database
// refreshing the DataGridView
}
In your sql query you missing the WHERE statement you in to indicat the ID of the costumer you want to delete
We did it guys. i use name instead of Id in where clause to handle data type exception. here is the working code of delete button.
`
`con.Open();
OleDbCommand comnd = new OleDbCommand();
comnd.Connection = con;
string q = "delete from customers where CustomerName='"
+ txtName.Text + "'";
comnd.CommandText = q;
comnd.ExecuteNonQuery();
MessageBox.Show("delete");

Single datagridview row updating

Could you help with such problem:
I have two forms, datagridview and SQL database.
On Load event of my first form I'm select some data from my SQL database by using stored procedure(select query).
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("PROC001", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;
After that, I can filter or sort my datagridview by using dt.DefaultView.Filter = .... and display in my grid only filtered rows.
On CellMouseDoubleClick event my second Form2 appearing. In this form I update some value in database by clicking on Button1 and also after that I want to update my selected datagridview row. My quetions are:
1) How can I update only selected row in datagridview and do not execute stored procedure for all datagridview filling again.
2) My datagridview is already filtered, so if I execute procedure again, my filter has been disapeared. How can I avoid of this?
3) On Form2 I'm updating some database value, that is not included in my "select query" as selected field, but this value is affected on this query. Example:
SELECT Name, SecondName FROM tUsers
WHERE id = (SELECT DISTINCT id FROM tProcedures WHERE Code = 'First')
In my datagridview I can see Name and SecondName, but in Form2 I'm updating Code in tProcedures database table. So after updating I want to see my new data in datagridview, only in selected row and with current filter. I don't want to SELECT all data again to datagridview and broke my filter.
Is it possible to update single row? Could you provide some examples?
Because the DataGridView is using DataBinding, you have to update the underlying data source, in this case the DataTable. See How to: Edit Rows in a DataTable for how to do that.
For the filter issue, you would want to save and restore the filter:
var filter = dt.DefaultView.RowFilter;
UpdateData();
dt.DefaultView.RowFilter = filter;

Categories