UpdatePanel doesn't Refresh - asp.net

I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.
I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method).
protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}

On a postback, when the page loads is the view of the hidden field what was posted back or is it the value you set when the page loads? It may be that you have to worry about the case where in the postback you aren't resetting a value to what it was originally. Another point is that if you do a delete, are you refreshing the data that you show or is it the same? Those would be my suggestions.

When I do a postback the value is the same what was postedback. I think updatepanel wasnt refresh. I tried to do __doPostBack('UpdatePanel1',''), didnt work either.

Related

How to prevent PostBack while clicking button in ASP.NET

The following picture is view of one of my WebForms in project. I am currently facing following problem: I am loading CSV file, the program analyzes it and displays it as a Table. Then, using DropDownLists and Textboxes below, user chooses day, project and hours in order to decrease hours, which have been assigned to the project (imagine project x, which has budget of 100.000$ and has 150h to be burned by workers. Each worker burns his own hours and web admin can see how many hours can be burned and how does the budget look like). When I decrease hours for some day, for example project x, Monday, 8h- the page reloads and all the things, including table, dropdownlists and textboxes are closed and user add project hours for another days.
Please see the code that is responsible for changes in the database and is executed during Submit button click:
private void decreaseProjHours()
{
if (IsPostBack)
{
string nameOfProject = DropDownList1.SelectedValue;
int dayID = DropDownList2.SelectedIndex;
int hours = Convert.ToInt32(TextBox3.Text);
if ((nameOfProject == "") || (dayID > 7 || dayID < 0) || hours < 0)
{
Response.Write("You have entered invalid data in one of the fields!");
return;
}
//decreasing from total hours assigned to project
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WorkTimeDBConnectionString"].ConnectionString);
conn.Open();
string getTotalProjectH = "select hours from projects where project_name='" + nameOfProject + "'";
SqlCommand com = new SqlCommand(getTotalProjectH, conn);
int check = Convert.ToInt32(com.ExecuteScalar().ToString());
if (check - hours < 0)
{
Response.Write("No more hours can be reported for project" + nameOfProject);
conn.Close();
return;
}
else
{
try
{
string tryUpdate = "update projects set hours='" + (check - hours) + "'" + " where project_name='" + nameOfProject + "'";
SqlCommand com1 = new SqlCommand(tryUpdate, conn);
com1.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
conn.Close();
return;
}
}
}
}
Is is the problem with PostBack? I already tried making OnClientClick return false and Button3.Attributes.Add("onclick", "return false;")- the operation of modifying the database fails then and nothing is submitted.
What should I do? Is it really problem with PostBack or something else refreshes my webpage?
EDIT:
Button3.Attributes.Add("onclick", "return false;");
Button3.OnClientClick = "decreaseProjHours(); return false;";
Button3.UseSubmitBehavior = false;
Thanks in advance,
Kokos
You have more or less the correct code in the line
Button3.OnClientClick = "decreaseProjHours(); return false;";
However the problem is that it looks for a javascript function decreaseProjHours(), which I'm assuming you don't have since you have that method on the server side in your code behind. OnClientClick is by definition a client-side handler and so the method needs to be defined on the client side. Since it can't find the javascript function, it fails to execute the next line return false;.
If you need that code to execute first and then return false to prevent postback, you need to put the code in a javascript function instead of in the code-behind. You can then have that fuction either return true or false if you wish, instead of having the additional return statement in the OnClientClick definition.
Note that if you have a server-side click handler defined as well, this won't execute if there is no postback; i.e. the server-side OnClick handler only executes if the client side returns true.

radGrid control displays blank grid after date parameter is changed

I searched SO, google & Telerik forums, but could not find a solution.
I have an existing app (written by a previous developer) that is calling a stored procedure that populates a RadGrid control. It populates fine the first time around.
However, when I change the date parameter, click "search" button, I get a blank RadGrid control. When I click search the second time, the grid is populated. When I walk through the code, I get an error message
Column 'ID' does not belong to table Table.
How can I resolve the issue of having to click search twice to display data ?
My code behind is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
try
{
ViewState["newset"] = null;
CreateDatasource();
this.RadGrid1.DataBind();
this.RadGrid1.CurrentPageIndex = 0;
ViewState["newset"] = "new";
string idex = this.hdnindex.Value;
if (idex != string.Empty)
this.RadGrid1.MasterTableView.Items[int.Parse(idex)].Selected = true;
}
catch (Exception ex) {
this.lblMessage.Text = ex.Message;
}
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
try
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
HyperLink hLink = (HyperLink)item["ViewHyperLink"].Controls[0];
if (hLink != null)
hLink.Attributes.Add("onclick", "selectMe('" + item.ItemIndex + "');");
}
}
catch (Exception ex)
{
this.lblMessage.Text = ex.Message;
}
}
In the code behind above, when this.RadGrid1.DataBind() is called, the code steps into RadGrid1_ItemCreated loops through the if statement a few times, them goes into the if statement, comes out of the function, and then the catch statement of btnSubmit is called, which displays the error message "Column ID does not belong to table Table".
Any ideas on how to resolve this?
Maybe you should try Grid - Simple Data Binding. Also you this thread (RadGrid NeedDataSource Page load) on telerik forum talks in detail about Simple Data binding. I don't know if you are trying to use NeedDataSource, but I have had similar issues before and the Simple Data binding worked perfectly.
That sure sounds like to me you need to call RadGrid1.Rebind() somewhere. Try calling that for your last line in your try block inside btnSubmit_OnClick.
Also, what does this search button do? Does it filter the results based on a date?

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

Linkbutton Dynamically Click

I have a problem with my project . I am creating link buttons dynamically to show the projects. When I click on a project it is firing and I can display link buttons of bugs dynamically . Now when I click on a bug , I want to display the description, dynamically too , but this click event is not firing , and I can't fix it .. This is my code .
private void LoadXmlBugs(XDocument xDocument)
{
//Load all bugs
IEnumerable<Bugs> data = from query in xDocument.Descendants("bugs")
where (((string)query.Element("bug_status") == "NEW") ||
((string)query.Element("bug_status") == "REOPENED") ||
((string)query.Element("bug_status") == "New"))
select new Bugs
{
Bug_Id = (string)query.Element("bug_id"),
Short_Desc = (string)query.Element("short_desc"),
Bug_Status = (string)query.Element("bug_status"),
Priority = (string)query.Element("priority"),
Creation_Ts = (string)query.Element("creation_ts"),
};
Bugs = new List<Bugs>(data);
string statut = Request.QueryString.Get("bug_status");
foreach (Bugs b in Bugs)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = ("~/Img/FolderIco.png");
PanelAllBugs.Controls.Add(img);
LinkButton lkButtonBugs = new LinkButton();
lkButtonBugs.Click += new EventHandler(lkButtonBugs_Click);
lkButtonBugs.ID = b.Bug_Id;
lkButtonBugs.Tag = b.Short_Desc;
lkButtonBugs.Text = b.Bug_Status + " " + b.Short_Desc + " " + "<br>";
lkButtonBugs.Attributes.Add("runat", "server");
PanelAllBugs.Controls.Add(lkButtonBugs);
}
}
void lkButtonBugs_Click(object sender, EventArgs e)
{
bugId = ((sender as LinkButton).ID);
LoadTheDescriptionForABug(bugId, ((sender as LinkButton).ID));
LoadBugsComments();
LoadBugsAttachments();
}
Can someone help me ?
Thank you very much .
from where do you call the method: LoadXmlBugs ?
dynamically added controls should be added at every PostBack so everything depends on where/when you are calling the method above.
try to call LoadXmlBugs from the Page_Init event handler.

Request Function Returns Null in Firefox/Chrome

I have a several form elements that I am dynamically creating with javascript when a user changes a number value in a textbox, by filling the innerHTML of a div like so:
dfinnerhtml = dfinnerhtml + "<div class='field'> ";
dfinnerhtml = dfinnerhtml + "<textarea name='textbox1" + suffix + "' type='text' id='textbox1" + suffix + "' value='' rows='4' cols='20' class='field'></textarea> ";
dfinnerhtml = dfinnerhtml + "</div> ";
Then, in the aspx.vb code behind, when the user clicks the Save button, I run through a series of Requests to try and add the values that are in these form elements to a SQL string:
Dim DFTestValue1 As String
DFTestValue1 = Request("textbox" & c.ToString)
where c is a loop counter to the # of textboxes created (the input value mentioned above that triggers the create)
The problem here is that this code works in Internet Explorer but not in Firefox or Chrome. The Request() value returns null and nothing is saved. I hope I've explained this well enough.
This post has probably got the answer:
http://forums.asp.net/t/1235816.aspx
Try the PreviousPage property:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox pTextBox = (TextBox)PreviousPage.FindControl("TextBox1");
Response.Write("Previous Page TextBox: " + pTextBox.Text);
}
}
For anyone that is interested to know, the problem was that a stray tag closed a div that preceded the tag. Internet Explorer didn't seem to care and counted items beyond this point as part of the form.

Resources