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

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();
}

Related

NullReferenceException when using SQL Queries WPF C#

I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database

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 get data when combo box is selected windows Form c#

private void namecombo_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = '" + this.namecombo.SelectedItem.ToString() + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach(DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
}
this doesn't work at all whats the problem?
You try to do it this way, just adapt it to your needs.
string sql = "SELECT * FROM Customers WHERE LastName = #lastName AND FirstName = #firstName";
UserAccount account = UserAccount.Empty;
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
{
SqlParameter _firstName = new SqlParameter("#firstName", SqlDbType.NVarChar);
SqlParameter _lastName = new SqlParameter("#lastName", SqlDbType.NVarChar);
_firstName.Value = account.FirstName;
_lastName.Value = account.LastName;
cmd.Parameters.Add(_firstName);
cmd.Parameters.Add(_lastName);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
if (dataSet.Tables.Count > 0)
{
if (dataSet.Tables[0].Rows.Count > 0)
{
DataRow row = dataSet.Tables[0].Rows[0];
//fill your properties with the results
}
}
adapter.Dispose();
dataSet.Dispose();
}
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = N'" + this.customergrid.SelectedRows + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach (DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}

Deleting data SQLServer using C# application

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();
}
}

How to get list of all database from sql server in a combobox using c#.net

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}

Categories