Deleting data SQLServer using C# application - c#

I need to make a button that delete rows from my dataset in C#, but I want datagridview selected rows to be deleted, how do I do that?
This is what was in the professor instructions, but unfortunatelly this isn't working for me.
int lineNum = int.Parse(lineDelete.Text.ToString());
SqlConnection sqlConn = new SqlConnection(ConnectionString);
sqlConn.Open();
string deleteSqlQuery = "select * from Clientes order by ID";
SqlDataAdapter deleteDA = new SqlDataAdapter(deleteSqlQuery, sqlConn);
DataSet deleteDS = new DataSet();
deleteDA.Fill(deleteDS, "Clientes");
deleteDS.Tables["Clientes"].Rows[lineNum].Delete();
SqlCommandBuilder deleteCB = new SqlCommandBuilder(deleteDA);
deleteDA.Update(deleteDS, "Clientes");
deleteDA.Dispose();
deleteDS.Dispose();
deleteCB.Dispose();
sqlConn.Close();
CliCadForm_Load(null, null);
CustTBoxID.Text = "";
CustTBoxNome.Text = "";
CustTBoxDDD.Text = "";
CustTBoxTel.Text = "";
CustTBoxEnde.Text = "";
CustTBoxENum.Text = "";
CustTBoxEComp.Text = "";
CustTBoxEBai.Text = "";
CustTBoxEUF.Text = "";
CustTBoxECid.Text = "";
CustTBoxECEP.Text = "";
lineDelete.Text = "";

If I understand you, you can use something like this:
private void DeleteSelectedRows()
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
foreach(DataGridViewRow row in dataGridView.SelectedRows)
{
SqlCommand cmd = new SqlCommand("DELETE FROM Clientes WHERE ID="+row.Cells["ID"].Value, con);
cmd.ExecuteNonQuery();
}
con.Close();
}
}

Related

Pulling sql data from [columnnr] to a string for a later check

I'm creating a small app. Until now I've had admin users hardcoded into the app, but I have the columns ready in the sql db to check if a user is admin or have edit rights. I'm just having trouble getting that info drawn out of the db.
And wanted to move on to being able to dynamically change admin users.
Heres the code from the app's Load
private void FrmMain_Load(object sender, EventArgs e)
{
if (labelUser.Text.Contains("JAM") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("DST") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("KBW") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("JDJ") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("THR") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else
{
btnAdmin.Visible = false;
btnUpdate.Visible = false;
btnNew.Visible = false;
}
//SQLconnection string
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
//SQLconnection
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
//Fill combobox list with items from the SQL database
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedItem = -1;
this.combo1.SelectedText = "--select--";
cmd.ExecuteNonQuery();
con.Close();
//SQLconnection
labelUser2.Text = labelUser.Text.ToLower();
SqlConnection con2 = new SqlConnection(cs);
con.Open();
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
DataSet ds2 = new DataSet();
using (SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
string IsAdmin = rdr["IsAdmin"].ToString();
labelisAdmin.Text = IsAdmin;
}
}
cmd.ExecuteNonQuery();
con.Close();
}
My first thought was to identify what user, by using my labelUser which is a visible label showing the user currently logged in taken directly from the sqldatabase. (reason for the .ToLower is that the sql db has the users in all small case).
First part of the sql is populating a combobox with items from another db tree.
It's this part that is causing me issues;
//SQLconnection
labelUser2.Text = labelUser.Text.ToLower();
SqlConnection con2 = new SqlConnection(cs);
con.Open();
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
DataSet ds2 = new DataSet();
using (SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
string IsAdmin = rdr["IsAdmin"].ToString();
labelisAdmin.Text = IsAdmin;
}
}
cmd.ExecuteNonQuery();
con.Close();
}
IsAdmin or column [3] is either 0 for false or 1 for true. but with this search, it doesnt return anything.
This is wrong
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
because you are actually looking for someone with a username of labelUser2.Text and not what that label's text property contains.
You were probably meaning to concatenate that into your string but that too is wrong. Although it would work, it is a very unsafe practice to get started with. Instead you would place a parameter into your sql statement and give it the value of your label.
string strCmd2 = "select * from tbl_Login where UserName = #un ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
cmd2.Parameters.Add("#un", SqlDbType.VarChar).Value = labelUser2.Text
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
...
Here we put a parameter in place to take in user inputted value, we then create the command object and define the parameters values from the user input controls.

How to delete multiple rows in C# using a SQL query?

I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}

There is already an open datareader error when filling Gridviews

I have looked at several posts already on trying to fix this issue and none of them are working.
I'm already using multiple active results.
I'm making sure to close the reader connections.
I'm using a different connection.
I'm using unique names for the reader, datatable, the reader, the command...
I am stuck.
The error is: There is already an open DataReader associated with this Command which must be closed first.
I have marked the error line with "*****error here *****".
Code:
protected void gridviewsched_RowDataBound(object sender, GridViewRowEventArgs e)
{
string nametime;
string name;
string time;
string initid;
string timeinitid = null;
GridView gridviewschedsub = (GridView)e.Row.FindControl("gridviewschedsub");
GridView gridviewschedcplt = (GridView)e.Row.FindControl("gridviewschedcplt");
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Public\\public website\\slDataBase.mdf;Integrated Security=True;Trusted_Connection=True; MultipleActiveResultSets=True;"))
{
con.Open();
DataTable dz = new DataTable();
dz.Columns.Add("age");
dz.Columns.Add("sex");
dz.Columns.Add("address");
if (e.Row.RowType == DataControlRowType.DataRow)
{
string id = gridviewsched.DataKeys[e.Row.RowIndex].Value.ToString();
using (var cmd = new SqlCommand("SELECT age,sex,address FROM precordTable WHERE Id='" + id + "'", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
//List<string> namedatelist = new List<string>();
while (reader.Read())
{
DataRow dr = dz.NewRow();
dr["age"] = reader[0].ToString();
dr["sex"] = reader[1].ToString();
dr["address"] = reader[2].ToString();
dz.Rows.Add(dr);
}
reader.Close();
}
gridviewschedsub.DataSource = dz;
gridviewschedsub.DataBind();
con.Close();
}
using (var cmd3 = new SqlCommand("SELECT name, initid FROM precordTable WHERE Id='" + id + "'", con))
{
con.Open();
using (SqlDataReader reader = cmd3.ExecuteReader())
{
List<string> namedatelist = new List<string>();
while (reader.Read())
{
name = reader["name"].ToString();
initid = reader["initid"].ToString();
time = DateTime.Now.ToString("MM-dd-yyyy");
time = Regex.Replace(time, "[^0-9a-zA-Z]+", "");
namedatelist.Add(name + time);
timeinitid = time + "$" + initid;
}
Session["timeinitid"] = timeinitid;
nametime = Regex.Replace(namedatelist[0].ToString(), "[^0-9a-zA-Z]+", "");
reader.Close();
}
}
var cmd2 = new SqlCommand("select case when exists((select * from [C:\\USERS\\PUBLIC\\PUBLIC WEBSITE\\SLDATABASE.MDF].INFORMATION_SCHEMA.tables where table_name = 'D" + timeinitid + "ou')) then 1 else 0 end", con);
if ((int)cmd2.ExecuteScalar() == 1)
{
string fQuery = "select item, scheduled from D" + timeinitid + "ou where 0 = 1";
string pQuery = "select item, scheduled from D" + timeinitid + "ou where initialed = '' and prescdr IS NULL and item != '';";
SqlDataAdapter sdyn = new SqlDataAdapter();
DataTable cpltTable = new DataTable();
cpltTable = GetData(pQuery);
gridviewschedcplt.DataSource = cpltTable;
gridviewschedcplt.DataBind();
con.Close();
}
else
{
return;
}
}
}
for (int j = 0; j < gridviewsched.Rows.Count; j++)
{
for (int i = 3; i < 9; i++)
{
gridviewsched.Rows[j].Cells[i].RowSpan = 2;
}
gridviewsched.Rows[j].Cells[2].RowSpan = 2;
}
}
private static DataTable GetData(string pQuery)
{
string schedtime;
string nowtime;
SqlDataAdapter sd1 = new SqlDataAdapter();
DataTable dTable = new DataTable();
using (SqlConnection conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Public\\public website\\slDataBase.mdf;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=True;"))
{
conn.Open();
SqlCommand cmd33 = new SqlCommand(pQuery, conn);
using (SqlDataReader reader99 = cmd33.ExecuteReader())
{
while (reader99.Read())
{
sd1.SelectCommand = cmd33;
***error here**** sd1.Fill(dTable);
DataRow newcpltTablerow = dTable.NewRow();
newcpltTablerow["item"] = reader99["item"].ToString();
dTable.Rows.Add(newcpltTablerow);
}
reader99.Close();
}
return dTable;
}
}
You do not need a SqlDataReader if you are using a SqldataAdapter. You are getting the error because you open a reader within an already open adapter. Do this instead (not compiled so tweak as needed and change the query to yours):
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
cmd33.ExecuteReader can only be called once. You are executing it for each row.

How I can manage to fill listview with .dbf

I'm trying to open .dbf via c# wpf and load it into a ListView, but I have no luck.
In my ViewModel:
public void DBF()
{
var databasePath = #"C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf";
var connectionString = string.Format("DSN=dBase Files", databasePath);
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();
var _command = connection.CreateCommand();
var query = string.Format(#"SELECT * FROM C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf");
string commandText = query;
var _dataAdapter = new OdbcDataAdapter(commandText, connection);
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
_dataSet.Reset();
_dataAdapter.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string userName = rows[0].ItemArray[1] as string;
string password = rows[0].ItemArray[2] as string;
UserDataVar = new InputDataSingle
{
UserName = userName,
Password = password
};
connection.Close();
}
Did I do something wrong? Any other ideas?
here you go. try below one.
string filename= //yourfilePath;
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filename +";Extended Properties=dBASE IV;User ID=Admin;Password=;";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + filename ;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
dt =ds.Tables[0]
}
here how to pass data to listview or dataGrid.;
mylistview.ItemsSource = dt.DefaultView;
Condition
you have to create View to your ListView;

Unable to compare the columns in SqlBulkCopy

Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
//matching columns
//SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
//SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
I know I need to add something like:
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
but I am not sure where I am supposed to add it in the above code
The column mappings are to be added to the bulkCopy.ColumnsMappings collection:
var mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
bulkCopy.ColumnMappings.Add(mapping1);
You do the mapping before you execute the WriteToServer call.
The MSDN documentation of SqlBulkCopyColumnMapping has further documentation and an example.

Categories