Deleting selected data from database C# - c#

May I know how to delete rows from the GridView using a LinkButton? Codes I find in google are using databound GridView. I'm binding the information depending on information selected with the DropDownList. Thanks
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string username;
username = HttpContext.Current.User.Identity.Name;
if (DropDownList1.SelectedValue.Equals("Expired"))
{
SqlConnection conn4 = new SqlConnection(My connection);
SqlDataAdapter adapter;
string mySQL2;
mySQL2 =
"SELECT Title,MessageStatus From Table_Message WHERE Username ='"
+ username
+ "' AND MessageStatus = 'Expired' AND Method = 'Email'";
adapter = new SqlDataAdapter(mySQL2, conn4);
conn4.Open();
DataSet ds3 = new DataSet();
adapter.Fill(ds3);
//Execute the sql command
GridView1.DataSource = ds3;
GridView1.DataBind();
conn4.Close();
}
else if (DropDownList1.SelectedValue.Equals("Pending"))
{
SqlConnection conn3 = new SqlConnection(My connection);
SqlDataAdapter adapter1;
string mySQL;
mySQL =
"SELECT Title,MessageStatus From Table_Message WHERE Username ='"
+ username
+ "' AND MessageStatus = 'Pending' AND Method = 'Email'";
adapter1 = new SqlDataAdapter(mySQL, conn3);
conn3.Open();
DataSet ds2 = new DataSet();
adapter1.Fill(ds2);
//Execute the sql command
GridView1.DataSource = ds2;
GridView1.DataBind();
conn3.Close();
}

If you are allowing anonymous users to access the listing:
This could be an option:
Create a delete.aspx
In your query do fetch Primary Key column (Ex: Id, UId...)
In grid view make DataKeyNames = "Id"
In linkbutton`s onclick Event, redirect user to delete.aspx?Id='Your data id'
The delete.aspx could only be accessed by the authorize users. Saves accidental data loss.
In delete.aspx put a delete button, and it`s onclick event delete the record with that Unique Id.
This could be a way doing things securely.
If you are displaying listing to only authorize users, then you may write the delete code with ajax:
OnClientClick(): Write javascript functio that send request to: delete.aspx?Id='Id', delete record there.

You can take the following steps
1) Map the DataKeyNames of grid to the primary key of your table
2) Have on LinkButton as
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="/_layouts/images/DELETE.GIF"
AlternateText="Delete" CommandName="DeleteUser" CausesValidation="false" ToolTip="Delete"/>
</ItemTemplate>
3) Bind the command argument in rowdatabound event
protected void GvwUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
ImageButton imgBtnDelete;
if (e.Row.RowType == DataControlRowType.DataRow)
{
imgBtnDelete = (ImageButton)e.Row.FindControl("imgBtnDelete");
imgBtnDelete.CommandArgument = gvwUser.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
4)In the code behind write the implementation as
protected void GvwUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = 0;
if (e.CommandName.Equals("DeleteUser"))
{
//get the user id
userId = Convert.ToInt32(e.CommandArgument.ToString());
//GetUser will delete the user
if (DeleteUser(userId) > 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Delete", "alert('User Deleted.');", true);
}
}

Related

How would I be able to grab the value from a drop down list control after the control has been bound with a filled data set?

How would I be able to grab the value from a dropdown list control after the control has been bound with a filled data set? Specifically, this control lives in my footer template and when the user tries to add a new row the selected item needs to be retrieved. The problem is after the dropdown list has been populated when you click on "add new" the value always returns null.
ROW COMMAND FUNCTION:
protected void userView_RowCommand(object sender, GridViewCommandEventArgs e)
{
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole");
string sqlCommandText = "INSERT INTO Users(USERNAME, PHONE, EMAIL, ROLEIDFK, DEPTIDFK, ACTIVE) VALUES(#username, #phone, #email, #roleidfk, #deptidfk, #active)";
scmd.Parameters.AddWithValue("#roleidfk", addUserRole.SelectedValue.ToString()); // >>>> Returns "AddUserRole was null"
}
DROPDOWN DATABINDING:
private DataTable GetData (string query)
{
var connection = sqlConnect.connect();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connection.ConnectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
protected void userView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
if ( e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
//query.addDataSetDdl(roles, "DESCRIPTION", "ROLEID", ddlUser);
ddlUser.DataSource = GetData("SELECT * FROM Roles");
ddlUser.DataTextField = "DESCRIPTION";
ddlUser.DataValueField = "ROLEID";
ddlUser.DataBind();
}
The problem is that the FindControl call does not use the correct id of the dropdpwnlist - at least it differs from the one that you use when databinding the dropdownlist:
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole")
vs
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
FindControl returns null if the control cannot be found, so if you use the correct id, the problem should be solved.

How to pass my hidden primary key value in a gridview to a stored procedure?

I have technically 5 columns in a gridview
EDIT and Deactivate button
Name
Phone
Email
[Hidden] userid "which is my primary key on the table"
I want to pass this userid value of the selected row to my update stored procedure that will set active=0 where userid=#userid.
Not sure if there is a way to pass a selecteddatakey or pass only the selected row hidden column 4 which would be 5 in index or if you have any other better ways.
protected void gvRowDeleting2(object sender, GridViewDeleteEventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_update_user_active";
cmd.Parameters.Add("#userid", SqlDbType.VarChar).Value = userID; ******NEED HELP HERE****
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
buildcontractoradmingv();
}
catch (Exception ex)
{
throw ex;
}
finally
{
/*Display message saying company is deactivated*/
string message = "User has been removed";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
con.Close();
con.Dispose();
}
}
Can you try this:
string UserID = YourGrid.Rows[e.RowIndex].Cells[IndexOfHiddenCol].Text;
The easiest way is to add userID as DataKeyNames to the GridView. userID in this case is a database column or property of the source bound to the GridView.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="userID"
Then get the value from the DataKeys in the delete method.
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Or you can add a Label to the TemplateField with the Visibility set to false.
<asp:Label ID="Label1" runat="server" Text='<%# Eval("userID") %>' Visible="false"></asp:Label>
And then get the value in code behind by using FindControl to look for the label and read it's Text.
Label label = GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;
int userID = Convert.ToInt32(label.Text);

binding grid view on button click in listview

I have a list view with a button for each row:
<td> <asp:Button ID="Button2" runat="server" Text="select" CommandName="view" CommandArgument='<%# Eval("inquiry_id")%>' onclick="buttonClick"/></td>
On click of this button i retrieve the id of the clicked row, set the session with the same id and bind the grid view.This the code behind the button click in list view:
ListViewItem item = (sender as Button).NamingContainer as ListViewItem;
Button butDetails = (Button)item.FindControl("Button2");
Int64 inquiryID = Convert.ToInt64(butDetails.CommandArgument);
Session["session_view_id"] = inquiryID;
this.BindGrid();
return;
The session is retrieved in bindGrid function. But the problem is gridview is not displayed at first click but on second click it gets displayed but with the data of the previous id clicked.The session is set but while binding the grid it uses old session value. Where am i going wrong to bind the grid?
The code for the bindGrid() function is :
int inquiryID = Convert.ToInt32(Session["session_view_id"]);
MySqlConnection conn = null;
try
{ MySqlCommand cmd = new MySqlCommand("SELECT * FROM crm_support_inquiry inner join crm_inquiry_perticipant on crm_support_inquiry.inquiry_id=?id inner join crm_mailer_types on crm_support_inquiry.mailer_id=crm_mailer_types.mailer_id limit 4", connect);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("?id", inquiryID);
cmd.Connection = connect;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
lblComp.Text = dt.Rows[0]["company"].ToString();
lblCname.Text = dt.Rows[0]["contact_name"].ToString();
lblEmail.Text = dt.Rows[0]["email"].ToString();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Are you checking for IsPostBack in your Page_Load method? You need to wrap your BindGrid call in your Page_Load in an if(!IsPostBack) statement to prevent the Page_Load from initially refreshing the data on postback. This can prevent the changes you are making later on in your event handler.
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
This answer can provide additional info: How to update page data after event handling?

Dropdown List Items Are Multiplying on clicking Gridview Select Button Each Time

Here is my Page Load Code
protected void Page_Load(object sender, EventArgs e)
{
string str = "SELECT BOOK.book_name,BOOK.price,BOOK.author,BOOK.publisher,BOOK.isbn,BOOK_APPROVAL.status,BOOK_APPROVAL.cat_id FROM BOOK INNER JOIN BOOK_APPROVAL ON BOOK.book_id = BOOK_APPROVAL.book_id";
SqlDataAdapter da = new SqlDataAdapter(str, obj.connect());
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
ds1.Clear();
DropDownList1.Items.Clear();
string str1 = "SELECT cat_id,cat_name from CATEGORY";
SqlDataAdapter da1 = new SqlDataAdapter(str1, obj.connect());
da1.Fill(ds1);
DropDownList1.DataSource = ds1;
DropDownList1.DataTextField = "cat_name";
DropDownList1.DataValueField = "cat_id";
DropDownList1.DataBind();
}
I have a dropdownlist, gridview with select button and a approve Button on the same page. When I click select button its values are displayed in series of textboxes and then i select a item from the dropdownlist. Its datavaluefield is assigned to a variable using the below code:
SqlCommand ddl = new SqlCommand("select cat_id from CATEGORY where cat_name='" + DropDownList1.SelectedItem + "' ", obj.connect());
catID = Convert.ToInt32(ddl.ExecuteScalar());
Finally when i click approve button values of all textboxes are inserted into the table where ID= dropdownlist.datavaluefield.
My problem is that when i click on the gridviews select button each time ,my dropdown list values are displayed Multiple times.
So, tried ds1.Clear() and DropDownList1.Items.Clear(); in page load, and it solved that problem, but it resets my Datavaluefield to '1'. So i can't insert into the table using selected datavaluefield.
So how can I solve this?
You just have to wrap the code in Page_Load in a !Page.IsPostBack-check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// code here that should be executed only at the first time
// and not on consecutive postbacks
}
}
The items are stored in ViewState by default in ASP.NET.

How to Save the data from a GridView to SQL Server 2005? How to Edit and Delete rows in the Gridview?

I have a GridView containing data extracted from two TextBoxes on click of a button. I want the following functionalities to be implemented in the Gridview:
1) I want to be able to Edit the data in this GridView.
2) I should also be able to Delete the rows from the GridView.
3) Finally, when I click on another Submit button, all the rows from the Gridview should be saved in the database.
Its a web-based ASP.NET application coded using C# (Visual Studio 2010), and uses SQL Server 2005. How can I make changes to the below code to implement the above specified functionality?
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
Session["data_table"] = dt;
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
ds.Clear();
da = new SqlDataAdapter("insert into PRACT values(#name, #city)", con);
con.Open();
da.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
con.Close();
}
}
Well on your aspx page I would recommend you to do that:
<asp:GridView runat="server" id="gvDisplay" OnRowCommand="grid_OnRowCommand">
<Columns>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtNameGrid" Text='<%#DataBinder.Eval(Container.DataItem, "Name")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtCityGrid" Text='<%#DataBinder.Eval(Container.DataItem, "City")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:Button runat="server" id="btnDeleteGrid" Text = "Delete" CommandArgument='<%#Eval(Container.DataItem, "YourIDColumn")%>' CommandName="DeleteRow"/>
</ItemTemplate>
</TemplateField>
</Columns>
</asp:GridView>
I recommend you to create a new column in your DataTable, this column will be the ID of each register.
Well, you add registers to this DataTable on your page, so you will need to create a session of type int and each time the event btnTextDisplay_Click is called you must increase this int Session and set it's value to the DataTable's Column ID.
The grid's attribute, OnRowCommand, is the event that will be called when you click on the button btnDeleteGrid. The code of this event comes below:
protected void grid_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "DeleteRow")
{
foreach(DataRow row in dt.Rows)
{
if(Convert.ToInt32(row["YourColumnID"]) == Convert.ToInt32(e.CommandArgument))
row.Delete();
}
dt.AcceptChanges();
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
Your event that will save the registers should be like that.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach(DataRow row in dt.Rows)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO YOUR_TABLE_NAME (NAME, CITY) VALUES (" + row["Name"].ToString() + "," + row["City"].ToString() + ")";
int numRegs = cmd.ExecuteNonQuery();
}
}
I really expect I helped.
I can't test my code and I'm not so good on work with DataTables, so if there's any problem with my code, just let me know.
I think it will be more efficient if you use Bulk Inserts to realize the inserts. Search for how to make it, it's pretty cool and quick.
And also try to use Stored Procedures, because it's safer than use direct command texts. Using them will prevent SQL Injection.
Best regards.

Categories