template field (button) of the grid executing on page refresh - asp.net

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?

Related

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

Capturing the value of dynamically created TextBox and DropDownList in ASP.NET

I am stuck in an issue, tried googling but could not find any solution.
I have created controls dynamically in Page_Load and I have a static button.
When the button is clicked, I need to capture user entry in those controls.
Now when I am trying to access the control using its unique id, error is being returned as the control is not available at runtime. :(
For loop - starts
if (dr["Type"].ToString().Trim() == "DropDown")
{
DropDownList ddl = new DropDownList();
ddl.Id = "ddl" + Convert.ToString(Counter);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = ds1;
ddl.DataBind();
ddl.EnableViewState = true;
cell.Controls.Add(ddl);
}
else if (dr["QuestionType"].ToString().Trim() == "TextBox")
{
TextBox txt = new TextBox();
txt.ID = "txt" + Convert.ToString(Counter);
txt.EnableViewState = true;
cell.Controls.Add(txt);
}
row.Cells.Add(cell);
table.Rows.Add(row);
Even if i do a FindControl in Btn_click function, it says that the panel has 0 controls.
var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");
textbox is always NULL, although I have a control txt5. I can see it when I do a F12.
Please help.
Dynamically created controls must be recreated on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set values and properties of controls specified in markup
...
}
// Create new controls and add them to the panel
...
}
They will then be available in the button event handler, and contain the data entered by the user.

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net

I have issue with viewstate of dropdown list [duplicate]

I have DropDownList that I have to populate in an event associated with a click event of another control.. the data is populated and present but when I select a value and postback the values are null. Which means the view state is not working.. Solutions say that populate the DropDown in Init() but I can't because the requirement does not allow this. I have to populate it on click event .. Viewstates are enabled.. The following code populates the DropDown..
if (e.CommandName == "Add Friend")
{
HtmlGenericControl divMySub = (HtmlGenericControl)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("divMySubjects");
divMySub.Style["display"] = "block";
DropDownList mySub = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
UpdatePanel mySubPanel = (UpdatePanel)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("UpdatePanelRequestAction");
DataView SubjectTableView = ProfileDataAccess.GetUserUnusedSubjectsForRequest(UserId ,RequesterId).DefaultView;
if (SubjectTableView.Count > 0)
{
mySub.DataSource = SubjectTableView;
mySub.DataTextField = "Name";
mySub.DataValueField = "Id";
mySub.DataBind();
}
else
{
divMySub.InnerText = "Requests Complete";
LinkButton buttonlink= (LinkButton)sender;
buttonlink.Enabled = false;
}
mySubPanel.Update();
}
and the following is the code for the postback that retrieves the value from the Dropdown list.. The DropDown is inside a Gridview Row.
protected void LinkButtonAddFriend_Command(object sender, CommandEventArgs e)
{
Guid RequestedId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
Guid UserId = new Guid(HiddenFieldUserId.Value.ToString());
int UserSubjectId = Convert.ToInt32 (GridViewUserSubjects.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
DropDownList DDL = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
LinkButton RequestAction = (LinkButton)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("LinkButtonFriendAction");
int RequesterSubjectId = Convert.ToInt32(DDL.SelectedItem.Value);
if (FriendsDataAccess.InsertRequest(UserId, RequestedId, UserSubjectId, RequesterSubjectId))
{
RequestAction.Text = "Remove Request";
RequestAction.Enabled = true;
}
}
DDL is the Dropdown with trouble.
When are you databinding the GridView which is the container of the DropDownList? Do you have wrapped it in a if(!IsPostBack)-check? When you databind the GridView the child controls are always "resetted".
If you use a declarative databound control like ObjectDataSource you should avoid this.databind() if it's not necessary.

DropDownList-Items are null on postback

I have DropDownList that I have to populate in an event associated with a click event of another control.. the data is populated and present but when I select a value and postback the values are null. Which means the view state is not working.. Solutions say that populate the DropDown in Init() but I can't because the requirement does not allow this. I have to populate it on click event .. Viewstates are enabled.. The following code populates the DropDown..
if (e.CommandName == "Add Friend")
{
HtmlGenericControl divMySub = (HtmlGenericControl)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("divMySubjects");
divMySub.Style["display"] = "block";
DropDownList mySub = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
UpdatePanel mySubPanel = (UpdatePanel)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("UpdatePanelRequestAction");
DataView SubjectTableView = ProfileDataAccess.GetUserUnusedSubjectsForRequest(UserId ,RequesterId).DefaultView;
if (SubjectTableView.Count > 0)
{
mySub.DataSource = SubjectTableView;
mySub.DataTextField = "Name";
mySub.DataValueField = "Id";
mySub.DataBind();
}
else
{
divMySub.InnerText = "Requests Complete";
LinkButton buttonlink= (LinkButton)sender;
buttonlink.Enabled = false;
}
mySubPanel.Update();
}
and the following is the code for the postback that retrieves the value from the Dropdown list.. The DropDown is inside a Gridview Row.
protected void LinkButtonAddFriend_Command(object sender, CommandEventArgs e)
{
Guid RequestedId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
Guid UserId = new Guid(HiddenFieldUserId.Value.ToString());
int UserSubjectId = Convert.ToInt32 (GridViewUserSubjects.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
DropDownList DDL = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
LinkButton RequestAction = (LinkButton)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("LinkButtonFriendAction");
int RequesterSubjectId = Convert.ToInt32(DDL.SelectedItem.Value);
if (FriendsDataAccess.InsertRequest(UserId, RequestedId, UserSubjectId, RequesterSubjectId))
{
RequestAction.Text = "Remove Request";
RequestAction.Enabled = true;
}
}
DDL is the Dropdown with trouble.
When are you databinding the GridView which is the container of the DropDownList? Do you have wrapped it in a if(!IsPostBack)-check? When you databind the GridView the child controls are always "resetted".
If you use a declarative databound control like ObjectDataSource you should avoid this.databind() if it's not necessary.

Resources