Updating rows on a table with condition - c#

I'm trying to delete all the rows, starting from the bottom of the table using a condition, but when that conditions is met then i want it to stop updating the table and leave the rest as it was. Example, if the last entry on the table meets it, delete it, if the one after it does not meet the condition then stop there, and exite the loop.
Here's the code i got, but its deleting all the rows :
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("A atualizar dados");
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab
WHERE serie ='1' AND tipodoc ='FSS'
AND contribuinte ='999999990'
and datadoc = CONVERT(varchar(10),(dateadd(dd, -2, getdate())),120)"
SqlCommand command = new SqlCommand(queryString, connection);
//command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * FROM wgcdoccab
WHERE serie !='1' and tipodoc !='FSS'
and contribuinte !='999999990'
and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120) ";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
MessageBox.Show("Dados Apagados com sucesso");
}
command.Connection.Close();
}
}
}
while (check);

Try something like this example:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE condition = false
)
For example, if you want to delete until a value is 4:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE tableName.Value = 4
)
If the table rows are:
|ID|Value|
| 1| 7|
| 2| 4|
Then the subselect will be 2 and no rows will be deleted. However, if the rows are:
|ID|Value|
| 1| 7|
| 2| 4|
| 3| 9|
| 4| 1|
Then the subselect will still return the ID of 2, and the last 2 rows will be deleted.

Related

some selected fields as Pivote column ASP.NET

I want to show some selected columns as my SQL column and the rest of the column should be pivot. My output should be: Please help me any idea ?
Pivot table
ID | Employee_ID | 01-sep-2019 | 02-sep-2019 | 03-sep-2019
───┼─────────────┼─────────────┼─────────────┼────────────
1 | 1001 | P | A | P
2 | 1002 | A | P | A
3 | 1003 | A | P | P
Original table
ID | Employee_ID |STATUS | Created_Date
───┼─────────────┼───────┼─────────────
1 | 1001 | P | 01-sep-2019
2 | 1002 | A | 02-sep-2019
3 | 1003 | P | 03-sep-2019
I use 2 `GridView to show data but it's applicable for all column that I don't need. Could you please help me?
private DataTable PivotTable(DataTable origTable) {
DataTable newTable = new DataTable();
DataRow dr = null;
//Add Columns to new Table
for (int i = 0; i <= origTable.Rows.Count; i++) {
newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
}
//Execute the Pivot Method
for (int cols = 0; cols < origTable.Columns.Count; cols++) {
dr = newTable.NewRow();
for (int rows = 0; rows < origTable.Rows.Count; rows++) {
if (rows < origTable.Columns.Count) {
dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
dr[rows + 1] = origTable.Rows[rows][cols];
}
}
newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
}
return newTable;
}
private void BindGridView() {
string strConnString = ConfigurationManager.ConnectionStrings["SQLDBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
try {
con.Open();
string sqlStatement = "SELECT Top(5)* FROM tbl_QC_Attandence";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt.Rows.Count > 0) {
//Bind the First GridView with the original data from the DataTable
grdorignal.DataSource = dt;
grdorignal.DataBind();
//Pivot the Original data from the DataTable by calling the
//method PivotTable and pass the dt as the parameter
DataTable pivotedTable = PivotTable(dt);
grdpivote.DataSource = pivotedTable;
grdpivote.DataBind();
}
} catch (System.Data.SqlClient.SqlException ex) {
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
} finally {
con.Close();
}
}
ORIGINAL TABLE
ID Employee_ID STATUS Created_Date
1 1001 P 01-sep-2019
2 1002 A 02-sep-2019
3 1003 P 03-sep-2019
PIVOT TABLE
ID Employee_ID 01-sep-2019 02-sep-2019 03-sep-2019
1 1001 P A P
2 1002 A P A
3 1003 A P P
I have create a dynamic query which can help you, but null can be replaced with 'A' in code side, try below one
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '',
#SelectColumnNames AS NVARCHAR(MAX);
SELECT
#columns += QUOTENAME([Created_Date]) + ','
FROM
Employee
ORDER BY
[Created_Date];
SET #columns = LEFT(#columns, LEN(#columns) - 1);
Select #SelectColumnNames = ISNULL(#SelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME([STATUS]) + ', 0) AS '
+ QUOTENAME([STATUS])
from (SELECT distinct [STATUS] from Employee) as Employees
print #SelectColumnNames
SET #sql =
N'Select * from(
select Created_Date,[STATUS],ID,Employee_ID
from Employee
)t
PIVOT(
MAX([STATUS])
FOR [Created_Date] IN ('+ #columns +')
) AS pivot_table
';
EXECUTE sp_executesql #sql;

C# & SQL server with data grid: Adding to A seperate database from data grid view

So, I know that you can populate information to a data grid from a SQL server. But is there a reverse process but to a different table to do so?
For instance having a master list and using other tables.
Example:
Master Table: (Displayed on datagrid1)
| OtherTableName| TestSubj | TestCriteria |
----------------------------------------------
| TableName | ValueSubj | ValueCriteria |
----------------------------------------------
| TableName | ValueSubj | ValueCriteria |
----------------------------------------------
Other Table
| TestSubj | TestCriteria |
-----------------------------
| ValueSubj | ValueCriteria |
-----------------------------
| ValueSubj | ValueCriteria |
-----------------------------
I want to pull the matching columns from a single row from Master Table(DataGridView1) to Other Table(SQL Database).
So essentially, you would click a row in DataGridView1 then click a button "Add Row to Other Table". Which would add your insert command to the SQL database, in this case it would Exclude the "OtherTableName" column and only insert the "TestSubj" and "TestCriteria" into "OtherTable" Table..
Is this at all possible? I've tried searching for some documentation on this, but I can't seem to find anything.
I'm sure there's a much simpler method in doing this.However, You can just use the strings from the selected rows cell Value. The user must select entire row You can change these settings in Visual Studio under datagridview properties.
private void button1_Click_1(object sender, EventArgs e)
{
string iOne = dgMasterGridView.SelectedRows[0].Cells[1].Value + string.Empty;
string iTwo = dgMasterGridView.SelectedRows[0].Cells[2].Value + string.Empty;
string iThree = dgMasterGridView.SelectedRows[0].Cells[3].Value + string.Empty;
string iFour = dgMasterGridView.SelectedRows[0].Cells[4].Value + string.Empty;
string iFive = dgMasterGridView.SelectedRows[0].Cells[5].Value + string.Empty;
string iSix = dgMasterGridView.SelectedRows[0].Cells[6].Value + string.Empty;
string iSeven = dgMasterGridView.SelectedRows[0].Cells[7].Value + string.Empty;
string iEight = dgMasterGridView.SelectedRows[0].Cells[8].Value + string.Empty;
string iNine = dgMasterGridView.SelectedRows[0].Cells[9].Value + string.Empty;
string iTen = dgMasterGridView.SelectedRows[0].Cells[10].Value + string.Empty;
string iEleven = dgMasterGridView.SelectedRows[0].Cells[11].Value + string.Empty;
string iTwelve = dgMasterGridView.SelectedRows[0].Cells[12].Value + string.Empty;
try
{
// Connection to DB
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Database;Integrated Security=True");
//Insert Query
string insertquery = "INSERT INTO dbo.[myTable] ([Item1], [Item2], [Item3], [Item4], [Item5], [Item6], [Item7], [Item8], [Item9], [Item10], [Item11], [Item12]) VALUES(#Item1,#Item2,#Item3,#Item4,#Item5,#Item6,#Item7,#Item8,#Item9,#Item10,#Item11,#Item12)";
SqlCommand cmd = new SqlCommand(insertquery, con);
//open connection
con.Open();
//Parameters
cmd.Parameters.AddWithValue("#Item1", iOne);
cmd.Parameters.AddWithValue("#Item2", iTwo);
cmd.Parameters.AddWithValue("#Item3", iThree);
cmd.Parameters.AddWithValue("#Item4", iFour);
cmd.Parameters.AddWithValue("#Item5", iFive);
cmd.Parameters.AddWithValue("#Item6", iSix);
cmd.Parameters.AddWithValue("#Item7", iSeven);
cmd.Parameters.AddWithValue("#Item8", iEight);
cmd.Parameters.AddWithValue("#Item9", iNine);
cmd.Parameters.AddWithValue("#Item10", iTen);
cmd.Parameters.AddWithValue("#Item11", iEleven);
cmd.Parameters.AddWithValue("#Item12", iTwelve);
//execute
cmd.ExecuteNonQuery();
//close connection
con.Close();
MessageBox.Show("Information has been submitted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This also skips the 1st column. However, If you wanted to pull the information from the 1st column, just add:
string iZero = dgMasterGridView.SelectedRows[0].Cells[0].Value + string.Empty;
&&
cmd.Parameters.AddWithValue("#Item0", iZero);
Don't forget to add it to your SQLQuery string also.
You can also Store the information in a Var for later use inside or outside of your scope.

CustomValidator on saving

There is a page (aspx), in it there is a text box (Brand auto) and the button on saving.
It is necessary that if in the Brand of the auto (in textbox) the user specified the following designations and pressed the button to save, shall work the validator and not save.
I created in a DB the table and procedure with these designations:
| ID | Name |
+----+-------+
| 1 | %BM% |
| 2 | %T-3% |
ALTER PROCEDURE [dbo].[vehicle_select]
#mark nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
if exists
(Select Name
From ogpo_specialize_vehicle
where #mark Like Name)
Select 1 as Vle
else
select 0 as Vle
END
I created QueriesAdapter.
Code:
protected void Mark_Validate(object source, ServerValidateEventArgs e)
{
(new DataSetVehiclesTableAdapters.QueriesTableAdapter()).ogpo_specialize_vehicle_select(Mark);
if(dt.VleColumn == 1 )
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}}
Help what to write in a condition? Conditions the wrong
in stored procedure add one more parameter: #Vle int;
Instead of SELECT 1 as Vle use Set #VLE = 1
The same thing for 0.
In code behind:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
SqlCommand cmd = new SqlCommand("procedure_name", con);
cmd.Parameters.Add("#mark", SqlDbType.NVarChar).Value = your_value;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
string result = cmd.Parameters["Vle"].Value.ToString();
con.Close();
Code:
protected void Mark_ServerValidate(object source, ServerValidateEventArgs args)
{
DataSetVehicles1TableAdapters.QueriesTableAdapter ds = new DataSetVehicles1TableAdapters.QueriesTableAdapter();
string mark = args.Value;
string result = ds.ogpo_specialize_vehicle_select(mark.ToUpper()).ToString();
if (result == "0")
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

Error adding from database to dropdownlist

I have a panel that is visible only when the Edit button from GridView is clicked.
In that panel is a form with a DropDownList and a TextBox where you can write a number and add it to a ListBox.
After all the numbers wanted are added to the ListBox when I click the button Finalize is adding to the database the data. In Gridview I have the name concatenate from database , because I have Lastname and Firstname separately.
To be more easy I chose to add from database in DropDownList when I click on Edit button with the specific ID.
When Edit button is clicked this error is showing:
Operation is not valid due to the current state of the object.
In the line where I add in DropDownList. I verified the names of my database, of my table , all and is correct. I even tried only with firstname , not concatenate and it does the same error. I don't know what is wrong. I hope you can help me. This is the code where the error appears.
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr[0].ToString());
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}
You are checking dr1.Read()
and reading dr[0].Tostring()
Also try to clear the list before adding the data. Then the index should be 1 if you need to show the name
it should be
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
}
I guess ID is numeric in query you are passing as .Text
try this
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME
FROM REFERENT_SHIPPING WHERE ID=" + Convert.ToInt32(grid.Cells[14].Text);
also all ways try to use parameterized query to avoide SQL INJECTION
Why you set ddl item from dr when you have dr1 as datareader.
Maybe you can try this:
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd = new OracleCommand(select_sql_SO, con);
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr = cmd.ExecuteReader();
OracleDataReader dr1 = cmd1.ExecuteReader();
int i=0;
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
i++;
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}

Fetch data from a database from two different tables

I am using C#(asp.net). I have two tables(data and details) in a same database.
Table "data"
id | chap | unit |
----------------
1| chap1|unit1 |
2| chap2|unit2 |
3| chap3|unit3 |
Table "details"
id| code| num |
----------------
1|abc |2 |
2|efg |3 |
3|hij |1 |
Now I want to fetch a value from "num" where code="efg" (in table "details"). And use the same value (3) to fetch data from table "data" by id. I am using this code.
OleDbConnection conn = new OleDbConnection(*** ...... *****);
OleDbCommand cmd;
OleDbDataReader reader;
String query = String.Format("select num from details where code="efg");
cmd = new OleDbCommand(query, conn);
reader = cmd.ExecuteReader();
int num = int.Parse(reader.GetValue(0).ToString());
query = String.Format("select chap from data where id={0}",num);
cmd = new OleDbCommand("select lesson from data where id=3", conn);
reader = cmd.ExecuteReader();
Label1.Text = reader.GetValue(0).ToString();
But it shows error. It shows "No data exists for the row/column."
You can use
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
WHERE de.code = 'efg'
or
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
AND de.code = 'efg'
More: if you're using SQL-Server, use SqlConnection in place of OleDbConnection.
More: don't format your query joining strings, numbers, dates and so on; use SqlParameter so you don't have to worry about types and formatting!!
Or you can use a subquery
SELECT * FROM data INNER JOIN
(SELECT num FROM details WHERE code='efg') det
ON data.id = det.num

Categories