C# DatagridVIew Delete SQL date - c#

How i make delete a data SELECTED(CHECKED) from MYSQL in datagridview in C# ?
My code:
string CONFIG = "server=localhost;userid=root;password=admin;database=program";
MySqlConnection cone = new MySqlConnection(CONFIG);
MySqlCommand query2 = new MySqlCommand();
query2.Connection = cone;
query2.CommandText = "DELETE FROM TABLE WHERE ID = #ID";
// I believe the key from this problem stay in line below//
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRows);
cone.Open();
query2.ExecuteNonQuery();
cone.Close();

SelectedRow property of the gridview gives the entire row . So you need to provide the column value (in you case it is ID) -
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRow
.Cells[indexofIDcolumn].Value)

Related

Why foreach loop does not work with datagridview selected rows in C#?

I am new to c# and using windows forms.
The following code loops through all selected rows in datagridview and take variables from cell0 and 4 as condition to use in sql query.
I multi-select rows then use this code and when I check the result in sql table I find this code only consider the first selected row in datagridview and ignore the rest.
Anyone knows how can I fix it, or what I am doing wrong? please help , thank you
foreach (DataGridViewRow row in DGV.SelectedRows)
{
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
MyConnection.Open();
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyCommand.Connection = MyConnection;
MyCommand.Parameters.Add("#_Delivery_State", SqlDbType.NVarChar).Value = button7.Text;
MyCommand.Parameters.Add("#_OrderNumber", SqlDbType.Int).Value = OrderNumber;
MyCommand.Parameters.Add("#_OrderDateTime", SqlDbType.DateTime).Value = OrderDateTime;
MyCommand.ExecuteNonQuery();
MyCommand.Parameters.Clear();
MyConnection.Close();
}
I multi-select rows then use this code and when I check the result in
sql table I find this code only consider the first selected row in
datagridview and ignore the rest.
That's too normal because you use same row cell as DGV.SelectedRows[0] in every iteration, not the rows that you iterate.
Change your
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
to
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
using(var MyConnection = new MySqlConnection(conString))
using(var MyCommand = MyConnection.CreateCommand())
{
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyConnection.Open();
foreach (DataGridViewRow row in DGV.SelectedRows)
{
MyCommand.Parameters.Clear();
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
MyCommand.Parameters.AddWithValue("#_Delivery_State", button7.Text);
MyCommand.Parameters.AddWithValue("#_OrderNumber", OrderNumber);
MyCommand.Parameters.AddWithValue("#_OrderDateTime", OrderDateTime);
MyCommand.ExecuteNonQuery();
}
}
I used AddWithValue in my example but you don't use this method. Use Add method overload as you did with proper MySqlDbType, not SqlDbType.

Update the first row of two columns in SQL table

I'm new to C# SQL. What im trying is to update existing Rows in my CurrencyRates Table which
has 2 columns buyEURrate and sellEURrate with type float.
on button click i want to change its values of its first rows
im getting the new data from 2 textboxes "EURbuyRate" and EURsellRate"
dont really know the syntax for it
var insertSQL = "UPDATE CurrencyRates (buyEURrate, sellEURrate) VALUES (#buyEURrate, #sellEURrate)";
string connectionString = #"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("buyEURrate", SqlDbType.Float);
cmd.Parameters.Add("sellEURrate", SqlDbType.Float);
cmd.Parameters["buyEURrate"].Value = float.Parse(EURbuyRate.Text.ToString());
cmd.Parameters["sellEURrate"].Value = float.Parse(EURsellRate.Text.ToString());
cmd.ExecuteNonQuery();
}
On button click for update "SqlCeException was unhandeled
System error "
From your posted code looks like you are using UPDATE statement like
UPDATE CurrencyRates (buyEURrate, sellEURrate) VALUES (buyEURrate, sellEURrate);
That syntax is for INSERT and not UPDATE. Your SQL statement should looks like
UPDATE CurrencyRates SET buyEURrate = buyEURrate,
sellEURrate = sellEURrate
WHERE some_condition;

Duplicating items in DataGridView c#

I have this code where I put data to the DataTable from where I show everything on DataGridView.
But when I look it contains information which supposed to be in file but its repeated twice.
Code to retrieve data from mysql database:
MySqlDataAdapter mySqlDataAdapter;
DataSet DS0 = new DataSet();
DataTable DT0;
string gender;
private void Filter()
{
ViewG.DataSource = null;
ViewG.Rows.Clear();
command.CommandText = "SELECT * FROM `table2` WHERE s1q2 = #gender";
command.Parameters.Add("#gender", MySqlDbType.VarChar);
command.Parameters["#gender"].Value = gender;
DT0 = DS0.Tables.Add("1Filter");
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
connection.Open();
mySqlDataAdapter.SelectCommand = command;
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
connection.Close();
}
Initially, on the start it retrieves all information from the database code (SELECT * FROM table) and displays on the DataGridView. And it works fine, but when I try to use filters to retrieve only for example "Females" problem occurs.
For full data I use:
mySqlDataAdapter.Fill(DS0.Tables["Full"]);
ViewG.DataSource = DS0.Tables["Full"];
For Filtered data:
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
If I run query used for filter on the application startup it does not duplicate and show correctly.
EDIT: SOLVED
From the code posted here, gender string is not assigned any value. So, your query be applying any filter that you want.
Thanks for you effort I found where the problem was. I used temp table on MySql and for some reason server did not dropped this table after connection is closed. So on the new query it added same items on the same table....

Updating SQL table with the contents of a datatable

I am creating an application in WPF using C# where users populate a datagrid and the information is then stored in a DataTable called smb1. The following code works for inserting the data into the SQL database but when I modify the code for updating it does not work. Does anyone know how I can modify my code to allow Updates as there are no errors thrown when I run my application in Visual Studio. I must add that the Equipment column cannot be edited in the datagrid so the returned data is the same as the data taken from the database so that the updated rows will be matched to the equipment rows in the SQL database using the WHERE clause. Below is the original insertion code plus my attempt for updating the database.
Insert Code
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "Insert into SHIFTLOG Values(#EQUIPMENT,#BATCHNO,#PRODUCTNO,#STATUS,#DATE,#PERIOD,#MACHINE)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in smb1.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#EQUIPMENT", row["EQUIPMENT"]);
sc.Parameters.AddWithValue("#BATCHNO", row["BATCHNO"]);
sc.Parameters.AddWithValue("#PRODUCTNO", row["PRODUCTNO"]);
sc.Parameters.AddWithValue("#STATUS", row["STATUS"]);
sc.Parameters.AddWithValue("#DATE", DateTime.Now.ToString("yyyy-MM-dd"));
sc.Parameters.AddWithValue("#PERIOD", DateTime.Now.ToString("tt"));
sc.Parameters.AddWithValue("#MACHINE", "SMB1");
sc.ExecuteNonQuery();
}
con.Close();
Attempt for Update Code
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "UPDATE SHIFTLOG SET EQUIPMENT='#EQUIPMENT',BATCHNO='#BATCHNO',PRODUCTNO='#PRODUCTNO',STATUS='#STATUS',DATE='2013-09-12',PERIOD='#PERIOD',MACHINE='#MACHINE' WHERE EQUIPMENT='#EQUIPMENT'";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in smb1.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#EQUIPMENT", row["EQUIPMENT"]);
sc.Parameters.AddWithValue("#BATCHNO", row["BATCHNO"]);
sc.Parameters.AddWithValue("#PRODUCTNO", row["PRODUCTNO"]);
sc.Parameters.AddWithValue("#STATUS", row["STATUS"]);
sc.Parameters.AddWithValue("#PERIOD", DateTime.Now.ToString("tt"));
sc.Parameters.AddWithValue("#MACHINE", row["MACHINE"]);
sc.ExecuteNonQuery();
}
con.Close();
Thanks for any help.
Remove the single quotes around the parameters.
string SqlCmdText = "UPDATE SHIFTLOG SET EQUIPMENT=#EQUIPMENT,BATCHNO=#BATCHNO,PRODUCTNO=#PRODUCTNO,STATUS=#STATUS,DATE='2013-09-12',PERIOD=#PERIOD,MACHINE=#MACHINE WHERE EQUIPMENT=#EQUIPMENT";
Also, I think the update section for EQUIPMENT=#EQUIPMENT is redundant, as the where clause will not be correct if it has changed. So you could use
string SqlCmdText = "UPDATE SHIFTLOG SET BATCHNO=#BATCHNO,PRODUCTNO=#PRODUCTNO,STATUS=#STATUS,DATE='2013-09-12',PERIOD=#PERIOD,MACHINE=#MACHINE WHERE EQUIPMENT=#EQUIPMENT";
remove the '' in all the parameters in your sql statement
"UPDATE SHIFTLOG SET BATCHNO=#BATCHNO,....... WHERE EQUIPMENT=#EQUIPMENT
if you use quotes all your parameters take as string values, not as SQL parameters
And also you need to use columns with [] like [DATE] if those are reserved keywords
How to deal with SQL column names that look like SQL keywords?

Using temporary table in c#

I read an excel sheet into a datagrid.From there , I have managed to read the grid's rows into a DataTable object.The DataTable object has data because when I make equal a grid's datasource to that table object , the grid is populated.
My Problem : I want to use the table object and manipulate its values using SQL server,(i.e. I want to store it as a temporary table and manipulate it using SQL queries from within C# code and , I want it to return a different result inte a grid.(I don't know how to work with temporary tables in C#)
Here's code to execute when clicking button....
SqlConnection conn = new SqlConnection("server = localhost;integrated security = SSPI");
//is connection string incorrect?
SqlCommand cmd = new SqlCommand();
//!!The method ConvertFPSheetDataTable Returns a DataTable object//
cmd.Parameters.AddWithValue("#table",ConvertFPSheetDataTable(12,false,fpSpread2_Sheet1));
//I am trying to create temporary table
//Here , I do a query
cmd.CommandText = "Select col1,col2,SUM(col7) From #table group by col1,col2 Drop #table";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText,conn);
DataTable dt = new DataTable();
da.Fill(dt); ***// I get an error here 'Invalid object name '#table'.'***
fpDataSet_Sheet1.DataSource = dt;
//**NOTE:** fpDataSet_Sheet1 is the grid control
Change your temp table from #table to ##table in both places.
Using ## means a global temp table that stays around. You'll need to Drop it after you have completed your task.
Command = " Drop Table ##table"
Putting the data into a database will take time - since you already have it in memory, perhaps LINQ-to-Objects (with DataSetExtensions) is your friend? Replace <int> etc with the correct types...
var query = from row in table.Rows.Cast<DataRow>()
group row by new
{
Col1 = row.Field<int>(1),
Col2 = row.Field<int>(2)
} into grp
select new
{
Col1 = grp.Key.Col1,
Col2 = grp.Key.Col2,
SumCol7 = grp.Sum(x => x.Field<int>(7))
};
foreach (var item in query)
{
Console.WriteLine("{0},{1}: {2}",
item.Col1, item.Col2, item.SumCol7);
}
I don't think you can make a temp table in SQL the way you are thinking, since it only exists within the scope of the query/stored procedure that creates it.
If the spreadsheet is a standard format - meaning you know the columns and they are always the same, you would want to create a Table in SQL to put this file into. There is a very fast way to do this called SqlBulkCopy
// Load the reports in bulk
SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString);
// Map the columns
foreach(DataColumn col in dataTable.Columns)
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
bulkCopy.DestinationTableName = "SQLTempTable";
bulkCopy.WriteToServer(dataTable);
But, if I'm understanding your problem correctly, you don't need to use SQL server to modify the data in the DataTable. You c an use the JET engine to grab the data for you.
// For CSV
connStr = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source={0};Extended Properties='Text;HDR=Yes;FMT=Delimited;IMEX=1'", Folder);
cmdStr = string.Format("SELECT * FROM [{0}]", FileName);
// For XLS
connStr = string.Format("Provider=Microsoft.JET.OLEDB.4.0;Data Source={0}{1};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'", Folder, FileName);
cmdStr = "select * from [Sheet1$]";
OleDbConnection oConn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand(cmdStr, oConn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
oConn.Open();
da.Fill(dataTable);
oConn.Close();
Also, in your code you ask if your connection string is correct. I don't think it is (but I could be wrong). If yours isn't working try this.
connectionString="Data Source=localhost\<instance>;database=<yourDataBase>;Integrated Security=SSPI" providerName="System.Data.SqlClient"
Pardon me, if I have not understood what you exactly want.
If you want to perform SQL query on excel sheet, you could do it directly.
Alternatively, you can use SQL Server to query excel (OPENROWSET or a function which I dont remember right away). Using this, you can join a sql server table with excel sheet
Marc's suggestion is one more way to look at it.
Perhaps you could use a DataView. You create that from a DataTable, which you already have.
dv = new DataView(dataTableName);
Then, you can filter (apply a SQL WHERE clause) or sort the data using the DataView's methods. You can also use Find to find a matching row, or FindRows to find all matching rows.
Some filters:
dv.RowFilter = "Country = 'USA'";
dv.RowFilter = "EmployeeID >5 AND Birthdate < #1/31/82#"
dv.RowFilter = "Description LIKE '*product*'"
dv.RowFilter = "employeeID IN (2,4,5)"
Sorting:
dv.Sort = "City"
Finding a row: Find the customer named "John Smith".
vals(0)= "John"
vals(1) = "Smith"
i = dv.Find(vals)
where i is the index of the row containing the customer.
Once you've applied these to the DataView, you can bind your grid to the DataView.
Change the command text from
Select col1,col2,SUM(col7) From #table group by col1,col2
to
Select col1,col2,SUM(col7) From ##table group by col1,col2

Categories

Resources