Delete all the data from the gridview - c#

I want to implement a button on a web page which deletes all the data that has been shown on the gridview. Is there any simpler way to delete all data at once with the button?

It's very simple to do. Just iterate over each row in the gridview with and get the primary key value, then using the sql query to delete the record from the database.
The code here can help you. I am using the NorthWind sample database.
void loaddata()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand();
connection.Open();
try
{
command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Employees";
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable datatable = new DataTable();
adapter.Fill(datatable);
GridView1.DataSource = datatable;
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int employee_id;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand();
connection.Open();
try
{
command = connection.CreateCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
employee_id = Convert.ToInt32(GridView1.Rows[i].Cells[0].Text);
command.CommandText = "DELETE FROM Employees WHERE EmployeeID = '" + employee_id + "'";
command.ExecuteNonQuery();
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
loaddata();
}

You can always just set the DataSource to null.
someGridView.DataSource = null;
someGridView.DataBind();

I can only be as vague as the question and I still don't quite understand why I can't leave comments, but I can leave an answer...
Anyway, we don't know what you're using to access your database or the model backing the GridView.
Let's say for instance you have the following class backing your GridView (the type of data your GridView consists of that you've set the Datasource to):
public class MyData
{
public int ID { get; set; }
public string SomeData { get; set; }
}
In your ASPX you'd have the following:
<asp:GridView ID="GridView" runat="server"></asp:GridView>
<asp:Button ID="DeleteButton" runat="server" OnClick="DeleteButton_Click"/>
And then in your code-behind, you'd do something like this...
protected void DeleteButton_Click(object sender, EventArgs e)
{
var gridViewItemsToDelete = (IEnumerable<MyData>)GridView.DataSource;
foreach (var idToDelete in gridViewItemsToDelete.Select(r=>r.ID))
{
// Delete the item by its ID
// I don't know what you're using to access your database
}
// Save Changes if you didn't in the foreach loop...
}

Related

Load Data from SQL Server into a combobox

I tried to get data from SQL Server (2 tables: Famille and Compte) into 2 comboboxes in the Form_Load().
But as you see the result, it works with the 1st combobox, but the 2nd it shows System.Data.SqlClient.SqlDataReader
This is the Code
private void Tresorerie_Load(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
String queryCompte = "select NomCom from Compte";
String queryFamille = "select NomFam from Famille";
commCompte = new SqlCommand(queryCompte, conn);
commFamille = new SqlCommand(queryFamille, conn);
try
{
//Compte
commCompte.CommandType = CommandType.Text;
dreaderCompte = commCompte.ExecuteReader();
while (dreaderCompte.Read())
{
queryCompte = dreaderCompte[0].ToString();
TreComBoxCompte.Items.Add(queryCompte);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Compte");
}
finally
{
dreaderCompte.Close();
}
try
{
//Famille
commFamille.CommandType = CommandType.Text;
dreaderFamille = commFamille.ExecuteReader();
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(dreaderFamille);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Famille");
}
finally
{
dreaderFamille.Close();
}
conn.Close();
}
For second combobox you are adding your datareader dreaderFamille:
TreComBoxFamille.Items.Add(dreaderFamille);
while you should add queryFamille:
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
If you pay attention to item texts in your ComboBox you will guess the problem and when you look at code, you will see your guess is true.
for 2nd comboxbox, you are using wrong object to add
TreComBoxFamille.Items.Add(queryFamille);
You should do it like this:
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
}

Combobox not filling from database C#

I'm trying to fill a combo box on from load from a database, I'm getting the error "Invalid object name 'POOL'"
Form load event to populate dropdown on form load
private void FRMAddTeam_Load(object sender, EventArgs e)
{
if (CMBBXPool.Items.Count > 0)
CMBBXPool.Items.Clear();
Database.CLSDB DatabaseClass = new Database.CLSDB();
DatabaseClass.FillDropDownList();
}
This is the code in my database connection class
public void FillDropDownList()
{
string PoolName = "";
Team.FRMAddTeam TeamAdd = new Team.FRMAddTeam();
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
Code to add the pool name
public void addPoolItem(string PoolName)
{
CMBBXPool.Items.Add(PoolName);
}
Any help is much appreciated
Your code needs to be:
public void FillDropDownList(Team.FRMAddTeam TeamAdd)
{
string PoolName = "";
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
You call it from your form like this:
DatabaseClass.FillDropDownList(this);
This will work, however it is strongly advised to change the implementation of your database class and remove tight coupling with GUI.
It is WRONG to fill your GUI from database class - instead of that, you should return data from your database class and bind your data to GUI in the GUI class.
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Object_orgy
http://en.wikipedia.org/wiki/Separation_of_concerns
Sounds like you dont have table Pool.Are you sure its there?
Log into your SQL management studio and use query analyzer to run the same command.
There could be many reasons for that If your schema is different or do you have permission to access that table ? or are you checking the right database ?
UPDATE:
You should try using SELECT [Name] FROM dbo.TBL_Pool

Sql command doesn't display table

I have this code behind button that displays table in SQL when the button is pressed.
I cant seem to know that problem why it doesn't display any table?
I added this line of code to check if the BatchID is out of range in the sql table
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header")
{
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DBcon"]))
{
if (String.IsNullOrEmpty(TextBox_ID.Text.ToString()))
{
lbl_NoBatchID.Text = "Please enter BatchID!";
}
else
{
try
{
lbl_NoBatchID.Text = "";
SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader Where BatchID =" + TextBox_ID.Text.ToString());
sqlCommand.Connection = con;
con.Open();
SqlDataReader read = sqlCommand.ExecuteReader();
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
}
catch (Exception)
{
}
}
}
}
Make sure you do two things.
1.) Close the DataReader after Databind().
2.) Set AutoGenerateColumns="True" for your GridView.

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

C# CheckBoxList update in SQL Server

Please inspect my C# code below and let me know where I am going wrong. Here is what I am experiencing:
1.) If I empty the SendReport column in SQL Server and load the page, the second row of the SendReport automatically gets populated with a 1.
2.) I can place a checkmark, click the button and the SendReport values successfully populate in SQL Server. However, if I uncheck any of them and click the button, none of the values change from 1 to 0. Please help!
$<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />
BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCheckBoxList();
}
}
// Setting up the ConnectionString
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}
// Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
CheckBoxList1.DataBind();
//Setting the Selected Items in the ChecBoxList based from the value in the database
//to do this, lets iterate to each items in the list
for (int i = 0; i < dt.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
{
CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
}
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
// Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
SqlCommand cmd;
string sqlStatement = string.Empty;
try
{
// open the Sql connection
connection.Open();
sqlStatement = "UPDATE Rorts SET SendReport = #SendReport WHERE Partner = #Partner";
cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Partner", name);
cmd.Parameters.AddWithValue("#SendReport", SendReport);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
// close the Sql Connection
connection.Close();
}
}
// Calling the Method for Saving the state of CheckBoxList selected items
protected void Button1_Click(object sender, EventArgs e)
{
string PartnerName = string.Empty;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
}
//ReBind the List to retain the selected items on postbacks
BindCheckBoxList();
}
It looks like the issue is due to the if block below from the Button1 click event handler. The result is that only the check boxes that are checked have the values persisted to the database.
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
You can just remove the if statement and persist all of the values or add logic to only persist those that have changed.

Categories

Resources