delete record from gridview but not from database - asp.net

I am trying to delete record from grid but not from Database.
I want to set database field ISDeleted 1 when data deleted from gridview but don't want to delete record from db.
My code delete records from both gridview and db.
Where to change in my code-
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
}
}
public void fillLanguageGrid()
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
if (chkdelete.Checked)
{
string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
// command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
deleteRecordByName(name);
}
}
fillLanguageGrid();
}
public void deleteRecordByName(string Name)
{
SqlConnection sqlConnection = new SqlConnection(strcon);
using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
{
// define this to be a stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
// define the parameter and set its value
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#IsDeleted", SqlDbType.Bit)).Value = 1;
command.Parameters["#status"].Value = "Delete";
//open connection, execute DELETE query, close connection
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Dispose();
}
}

For that you need to add a column in your respective database table whether to show that record or not.For Ex: add column like Visible int.
Assume if
Visible =1 --> Show that record in gridview
Visible =0 --> Hide that record in gridview
By default make Visible =1 so all records are shown in gridview(write the query like Select ......Where Visible =1).when you try to delete record use update query that need to update Visible column 1 to 0.So your gridview only shows records where visible =1 .That particular deleted record is not shown in your gridview because its Visible column is 0.Try this..

Related

While inserting new record into database, it is updating old record in grid view

Grid view updating old record, when i'm trying to add new record.
In grid view I have a edit option. If I click on edit, the particular row is going to edit screen and filling textboxes and updating as expected. When clicking on add new record button in grid view, it is going to add screen with empty textboxes as expected, but if I add a new record, it is updating the previous record which was edited.
protected void GV_PRIOR_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int pid = Convert.ToInt32(GV_PRIOR.DataKeys[e.NewSelectedIndex].Value);
DataTable dt = bll.editprior(pid);
foreach (DataRow dr in dt.Rows)
{
HiddenField1.Value = dr["P_ID"].ToString();
tb_prioname.Text = dr["P_NAME"].ToString();
chk_actprior.Checked = dr["P_ACTIVE"].ToString() == "Y";
}
btn_savprior.Text = "UPDATE";
}
protected void btn_savprior_Click(object sender, EventArgs e)
{
if (HiddenField1.Value == "")
{
bll.savprior(0, tb_prioname.Text, Convert.ToBoolean(chk_actprior.Checked));
Response.Write("<script>alert('Priority Saved Successfully')</script>");
}
else
{
bll.savprior(Convert.ToInt16(HiddenField1.Value), tb_prioname.Text, Convert.ToBoolean(chk_actprior.Checked));
Response.Write("<script>alert('Priority Updated Successfully')</script>");
}
bindgrid();
}
If I click on the add new record button, after filling textboxes it should add a new record, but it is updating the old record which was edited just before adding new record.
Stored Procedure:
ALTER PROC [dbo].[SAVEPRIOR]
#P_ID int,
#P_NAME varchar(20),
#P_ACTIVE char(1)
AS
BEGIN
IF(#P_ID=0)
BEGIN
INSERT INTO PRIORITY(P_NAME) VALUES (#P_NAME)
END
ELSE
BEGIN
UPDATE PRIORITY SET P_NAME=#P_NAME,P_ACTIVE=#P_ACTIVE WHERE P_ID=#P_ID
END
END
DAL:
public void savePRIOR(int id, string priorname, bool actv )
{
SqlCommand cmd = new SqlCommand("SAVEPRIOR", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#P_ID", id);
cmd.Parameters.AddWithValue("#P_NAME", priorname);
cmd.Parameters.AddWithValue("#P_ACTIVE", (actv) ? "Y" : "N");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
BAL:
public void savprior(int id, string priorname, bool actv )
{
dll.savePRIOR(id, priorname, actv);
}
Try to clear the HiddenField1.Value="";
before bindgrid();

When I Update in Custom GridView then TextBox was return null

I'm trying to update data in GridView and when I click on Edit then data was bound and display in TextBox but when I click on Update and debug it then TextBox return null value and update with that null value
protected void grdCustomer_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtUserName = (TextBox)grdCustomer.Rows[e.RowIndex].FindControl("txtUserName");
command = new SqlCommand("Users_Update", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("Names", txtUserName.Text);
command.ExecuteNonQuery();
grdCustomer.EditIndex = -1;
GetData();
}

ASP.NET DropdownList Always insert the first item

I have dropdownlist on my website. When I select the any item to insert the database but it does not insert selected item always insert the first item inside the dropdown list. Please Help How can I solve that problem?
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategory();
}
}
void GetCategory()
{
dlCategory.DataSource = Data.GetDataTable("SELECT * FROM tblCategory");
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}
SqlConnection baglanti = Data.baglan();
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values(#CategoryID)", baglanti);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
Your question is a bit blurry regarding the code, so correct me if I misunderstood, but I presume you want to do the following in WebForms:
Simply show all available categories that can be assigned to a
product
When the user selects the category and hits submit, it will be inserted to the DB assegnied to it
It is not quite elegant, but I would put something like this:
private SqlConnection _sqlConnection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
_sqlConnection.ConnectionString = #".." //Assign whatever your ConnectionString is in Data.baglan();
_sqlConnection.Open();
if (!IsPostBack)
{
GetCategory();
}
else
{
//Define your insert something like this, and I would put this into the submit Button_Click event:
if (!String.IsNullOrEmpty(dlCategory.SelectedValue) && dlCategory.SelectedValue != "0")
{
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values (#CategoryID)", _sqlConnection);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
}
else
{
//TODO: Handle wrong selection, eg display an error message..
}
}
}
void GetCategory()
{
dlCategory.DataSource = new SqlCommand("SELECT * FROM tblCategory", _sqlConnection).ExecuteReader();
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}

asp.net gridview edit button doesn't update

When I enter new data and press update button it saves the old data (data that I want it to update).
public void fill()
{
SqlCommand cmd = new SqlCommand("select * from school ",con );
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
fill();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
string stu =((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int age = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
SqlCommand cmd = new SqlCommand("UPDATE school SET stu_name=#stu_name,age=#age where id=#id ", con);
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#stu_name", stu));
cmd.Parameters.Add(new SqlParameter ("#age",age));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fill();
}
he problem that the values that assigned to name,age are the existing values in the database not the new values which I entered in the runtime
any one can help me??
thanks in advance
You are repopulating the grid every time you edit it.
Call fill(); on grid init instead.
Here's some info on the Life Cycle of a web form. I think all you need is to wrap your fill(); in an if statement. Because page_load happens before your event handler, you reload from the db on top of the values that were entered.
if(!PostBack)
{
fill();
}

Dropdownlist on gridview updating only first value to the database ASP.Net

I am looking for the solution to this problem from many days, please help.
I have a grid view and have five dropdownlist on it. I have edit update and cancel edit buttons on each row.
Drop down list is updating the database, but only first value in the dropdownlist even when user select second, third or any other value from the dropdownlist.
What could possible be the reason for this. Here is my row Edit/ CancelEdit and Updating Events.
protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblCustId = (Label)gvCustomers.Rows[e.RowIndex].FindControl("cust_id");
DropDownList ddlCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("CSM");
DropDownList ddlSrCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("SrCSM");
DropDownList ddlDE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("DE");
DropDownList ddlAE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("AE");
DropDownList ddlTE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("TE");
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string sql = "Update SOME_TABLE SET CSM= #CSM, SrCSM= #SrCSM ,DE=#DE,AE=#AE,TE=#TE where cust_id=#cust_id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CSM", SqlDbType.VarChar).Value = ddlCsm.SelectedItem.Value;
cmd.Parameters.Add("#SrCSM", SqlDbType.VarChar).Value = ddlSrCsm.SelectedItem.Value;
cmd.Parameters.Add("#AE", SqlDbType.VarChar).Value = ddlAE.SelectedItem.Value;
cmd.Parameters.Add("#DE", SqlDbType.VarChar).Value = ddlDE.SelectedItem.Value;
cmd.Parameters.Add("#TE", SqlDbType.VarChar).Value = ddlTE.SelectedItem.Value;
cmd.ExecuteNonQuery();
}
}
catch
{ }
gvCustomers.EditIndex = -1;
BindData();
}
}
Any help would be greatly appeciated.
Thanks
just fill the dropdowns on the click of edit button and then use on rowupdating event and use ddl.SelectedValue instead of ddl.SelectedItem.Value. You will find the selected values.
Your Drop Downs are probably getting re-set in your Page_Load event. If they are, load them when the page is not in postback, like so:
if(!Page.IsPostBack) {
//set drop downs
}

Resources