When I Update in Custom GridView then TextBox was return null - asp.net

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

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

GridView RowCommand update send variable to javascript function

I have a Gridview that has an update link on it. Once "Edit" is selected from one of the rows the values in that row in the grid change into text boxes and can be edited. The "edit" button disappears and changes into an "update" link. Then the user edits the contents of one (or more than one) of the text boxes and "update" is selected. A JavaScript confirmation box appears asking if the user wants to update the values(s) and the changes are saved or discarded depending upon the choice selected. This is performed by "OnClientClick"
However I want to validate the change server side and pass back a defined error message to the user if the validation has failed. Example; if registered company name in the wrong format has been entered into one of the text boxes in the row selected.
The grid row will then remain in an editable state until the user corrects the error. The operation can be discarded by selecting "Cancel" from the grid row (I already have this functionality).
The C# rowcommand function is:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
}
The ASPX is
<asp:LinkButton ID="lnkUpdate" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return ConfirmOnUpdate();" CommandName="Update" > Update</span></asp:LinkButton>
The javascript is
function ConfirmOnUpdate()
{
if (confirm("Are you sure you want to update this record?"))
return true;
else
return false;
}
Thank you for any replies
Use this code for handling server side validation.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
if (myTextBox_registered_company_name.Text != "") // add your validation in this if block, now it checks textbox is not empty;
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
else
{
ScriptManager.RegisterStartupScript(this,this.GetType(),"Error Message", "alert('TextBox is empty!')",true);
}
}

delete record from gridview but not from database

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..

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
}

template field (button) of the grid executing on page refresh

I have a button as template field in my hierarchical grid and on that button I am updating some data but when user hit the browser refresh button it executes by itself ..whats the solution..
here is my code behind
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (!Page.IsPostBack)
{
if (e.CommandName == "UpdateBillData")
{
GridViewRow row = ((Control)e.CommandSource).NamingContainer as GridViewRow;
int index = row.RowIndex;
int billgenID = Convert.ToInt32(GridView1.DataKeys[index].Value);
DropDownList ddmonths = (DropDownList)row.FindControl("DDBillingMonths");
TextBox cunit = (TextBox)row.FindControl("txtCurrBillUnits");
TextBox amountbDue = (TextBox)row.FindControl("txtAmountBDueDate");
TextBox advItax = (TextBox)row.FindControl("txtAdvIncomeTax");
TextBox whtax = (TextBox)row.FindControl("txtWholdingTax");
TextBox gst = (TextBox)row.FindControl("txtGst");
TextBox amountafterdd = (TextBox)row.FindControl("txtAmtAfterDD");
TextBox duedate = (TextBox)row.FindControl("txt_BillDueDate");
TextBox billingdate = (TextBox)row.FindControl("txt_BillGenDate");
TextBox remarks = (TextBox)row.FindControl("txtOthers");
//Update Bill Data Procedure
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("sp_Update_GenBill");
db.AddInParameter(cmd, "#gridrowID", System.Data.DbType.Int32);
db.SetParameterValue(cmd, "#gridrowID", billgenID);
db.AddInParameter(cmd, "#bmonth", System.Data.DbType.String, 3);
db.SetParameterValue(cmd, "#bmonth", ddmonths.SelectedValue);
//Execute Stored Procedure
int i = 0;
i = db.ExecuteNonQuery(cmd);
if (i != 0)
{
showalert("Succesfuly Updated...");
}
else
showalert("Error occured while updating...");
}
}
}
My guess is your last postback before each refresh was a control with a command associated with it. When you hit REFRESH in your browser, it actually reposts the command. Try just going to your browser's address field and hitting ENTER. Do you get the same results?

Resources