updatepanel problem or possible bug - c#

I have TextBox (multiline) and Label in an UpdatePanel which I refresh with javascript __doPostBack(upEditReminder,id);
Then I set both Label and TextBox text to current DateTime.
protected void upReminder_Onload(object sender, EventArgs e)
{
lbTest.Text = DateTime.Now.ToString();
tbReminder.Text = DateTime.Now.ToString();
Problem is that Label is updated but TextBox date is updated only once when the page is loaded but not when __doPostBack(upEditReminder,id); is triggered.
I cant figure out what the problem is.
I have also tried textarea runat="server" but still have the same problem.
Your help is much appreciated.

This worked for me... is it different from what you're doing?
aspx code snippet:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
Update
codebehind snippet:
protected void UpdatePanel(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
TextBox1.Text = DateTime.Now.ToString();
}
Clicking the "Update" link triggers the UpdatePanel's postback which refreshes it via ajax and both the label and textarea get the updated timestamp.

Could you try it after setting EnableViewState as false in that textbox?

Are you setting the textbox text anywhere else in your code behind? I'm guessing it's getting overwritten somewhere...

Add a button inside the UpdatePanel. Click the button, does it update both label and textbox?
In addition, the call you are making should have the ClientID of the updatepanel which looks something like this:
__doPostBack("ctrl00_ctrl01_upEditReminder",'');

From one of your comments I noticed that you are trying to update a textbox outside of the updatepanel. The problem here is that you cannot update something outside the updatepanel in the updatepanel's postback. That's one of the drawbacks of using an updatepanel.
If you still want to use an updatepanel, I suggest that you update the other page's elements using javascript and preferrable jQuery after the updatepanel reload. You could use a hidden input field inside the updatepanel to transfer the data. To refresh the textbox after the update, you could use this JavaScript/jQuery code:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
var reminder = $("[id$='hidReminder']").val();
$("[id$='tbReminder']").val(reminder);
});

Related

Textbox does not clear in firefox

txtName is the first control in the page. When the page loads initially, it is empty. If there is text in the textbox and the user clicks on Refresh, it is not clearing the text.
At debug, i can see the textbox being cleared, but on page it isnt!!!!.
This happens in Firefox. Works fine in IE.
I have tried , Keeping the textbox outside the updatepanel, enveloping another updatepanel for this textbox alone, Enabling the viewstate, and also removing the clientidmode property.
ASPX:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBack ControlID="txtName" EventName="TextChanged"/>
</Triggers>
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server" OnTextChanged="txtName_TextChanged"
EnableviewState="false" ClientIDMode="Static">
</asp:TextBox>
//Some other controls
</ContentTemplate>
</asp:UpdatePanel>
C#:
protected void page_load()
{
if(!IsPostBack)
{
txtName.Text="";
UpdatePanel1.Update();
}
}
protected void page_load()
{
if(!IsPostBack)
{
UpdatePanel1.Update();
}
txtName.Text="";
}
Try this way
Please add txtName.Text=""; outside if condition. Try like this.
protected void page_load()
{
txtName.Text="";
if(!IsPostBack)
{
UpdatePanel1.Update();
}
}
An alternative solution is to set autocomplete=off on your textbox, which will work on FF.
If you do need autocompletion, you can wrap your code into a form. and reset it in the onLoad event
<form id="autoclearform">
//your textboxes
</form>
Now either add onload="autoclearForm.reset();" to your body or do it via javascript.
$(document).ready(function() {
autoclearForm.reset();
});

change masterpage image src from page in update panel C#

I have a master page that contains an image as follow:
<asp:Image ID="imgCompanyLogo" runat="server" ImageUrl="image path" />
and in a child page I want to edit the property ImageUrl as follow:
Image imgCompanyLogo = (Image)Page.Master.FindControl("imgCompanyLogo");
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
and it doesn't give me an exception, but it doesn't change anything.
Note: I have an UpdatePanel in the child page.
Since the image is sitting outside of the UpdatePanel, server side changes will not be executed on the image after a partial postback. Your only option is to inject JavaScript into the page and change the image URL.
Use the ScriptManager.RegisterStartupScript Method to inject JavaScript after the partial postback.
Something like the following will work for you:
C#
protected void btnPostback_Click(object sender, EventArgs e)
{
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
ScriptManager.RegisterStartupScript(btnPostback,this.GetType(), "myScript", "ChangeImage('" + ImageUrl + "');",false);
}
JavaScript
function ChangeImage(imgURL) {
//make sure the ID of the image is set correctly
document.getElementById('imgCompanyLogo').src = imgURL;
}
Wrap image by UpdatePanel with UpdateMode="Always"
Master Page:
<asp:UpdatePanel runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Image runat="server" ID="Image1" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
public void SetImageUrl(string url)
{
Image1.ImageUrl = url;
}
Child Page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button Text="Click Me" runat="server" OnClick="UpdateImage" />
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateImage(object sender, EventArgs e)
{
((Main)Master).SetImageUrl("~/Images/0306d95.jpg");
}
The code above works well for me.
Have a look at Sys.WebForms.PageRequestManager Class. Define handler in javascript and may change the image source.
If your code is being run after an async postback (per your UpdatePanel) then changes to anything outside the UpdatePanel will not be rendered. Content in the master page would definitely seem to qualify.
If this is what you're trying to do, this model won't really work. You will need to use some client script to effect changes to already-rendered content when working with this model.
An UpdatePanel is a construct to identify an area that's updated through ajax. The page is not actually reloaded. So an postback can never change content that's outside of the UpdatePanel (or control bound to that panel) that sourced it.
Here's a basic implementation (using jQuery). Add a hidden field to pass the new source to the client. This must be inside the UpdatePanel. Change this value from the server when you want the image to update with new_image_src.Value=ResolveUrl(...);
<asp:HiddenField ClientIdMode="Static" runat="server" id="new_image_src"
value="" EnableViewState="false">
Give your image a static id too to make life easier:
<asp:Image ClientIdMode="Static" runat="server" id="dynamic_image" ImageUrl="..." >
Add javascript to the page (should NOT be in the UpdatePanel):
function updateImage() {
var new_src=$('#new_image_src');
if (new_src) {
$('#dynamic_image').attr('src',new_src);
/// erase it - so it won't try to update on subsequent refreshes
new_src.val('');
}
}
$(document).ready(function() {
/// adds an event handler after page is refreshed from asp.net
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(updateImage);
});
This wouldn't be difficult to do without jquery either but seems more common than not these days.

Bind the asp control while typing the text in Text box

I have a text box and a repeater control. I need to bind the data to repeater control when a user is entering the text in text box. This should happen without clicking on the enter key or mouse click.
Repeater should be binded with the names starts with the given string in the text box
anybody have an idea?
I am assuming that what you want is to enter the same value from the textbox on to a repeater column.
You can use the onchange event of the textbox to call javascript and update your repeater.
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server" /> <div id="Container"> <asp:UpdatePanel runat="server" ID="UpdatePanel1"
OnLoad="UpdatePanel1_Load"> <ContentTemplate>
<asp:Repeater runat="server" ID="rpt"></asp:Repeater> </ContentTemplate> </asp:UpdatePanel>
<input type="text" id="Container" onkeyup='update(document.getElementById("Container").value)'>
JS
function update(args)
{
__doPostBack('UpdatePanel1', args);
}
C#
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
//bind reapeter
}
Got it.. This http://www.dotnettutorials.com/tutorials/ajax/ajax-search-csharp.aspx helps me to get what exactly I want with minor changes.

How to update controls[DataGrid,TextBoxes and Label] based on a row selection made in DataGrid that resideds in a updatePanel?

I have got a grid[Grid1] that build its dataRows when a button[search] is clicked, I managed to Ajaxify it by placing it in an UpdatePanel and it worked fine. Before Ajaxifying Grid 1, another grid[Grid2] and some other controls[Text and Labels] used to get populated/updated when a row in Grid 1 was clicked .
The Grid2 and other controls used to get populated/updated on the OnItemCommand Event of Grid 1.Its the code in the OnItemCommand that binds the related data to Grid2 and other controls.
After I placed the Grid 1 in the update panel,they stopped updating. It will work fine if I place Grid2 and other controls in the same Update Panel but the page is designed in a way that I cant have those controls in the same UpdatePanel as the first Grid nor I dont intend to use another Update Panel.
I hope I'm making some sense. I'm a newbie in .Net so please excuse. Please find the code below.
<asp:ScriptManager EnablePartialRendering="true" ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers ="True">
<ContentTemplate>
<asp:DataGrid ID="grdJobs" runat="server" AllowPaging="true"
AlternatingItemStyle-CssClass="gridAltItemStyle"
AutoGenerateColumns="False" CellPadding="0"
DataKeyField="code"
CssClass="datagridBox"
GridLines="horizontal"
PagerStyle-Mode="NumericPages"
HeaderStyle-CssClass="gridHeaderStyle"
ItemStyle-CssClass="gridItemStyle"
PagerStyle-CssClass="gridPagerStyle"
Width="445px" OnPageIndexChanged="grdJobs_PageIndexChanged" OnItemCreated="grdJobs_ItemCreated" OnItemCommand="grdJobs_ItemCommand" OnItemDataBound="grdJobs_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="J_ID" HeaderText="Job"></asp:BoundColumn>
<asp:BoundColumn DataField="Contract" HeaderText="Contract" ReadOnly="True"></asp:BoundColumn>
<asp:BoundColumn DataField="J_Fault_Line1" HeaderText="Fault" ReadOnly="True"></asp:BoundColumn>
<asp:BoundColumn DataField="j_p_id" HeaderText="Fault" Visible="false" ></asp:BoundColumn>
<asp:ButtonColumn Text="<img src=images/addFeedback.gif style=border: 0px; alt=Add Feedback>" ButtonType="LinkButton" HeaderText="Add" CommandName="Load" ItemStyle-cssClass="Col_9_Item_2"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
<asp:ImageButton ID="cmdLkp" ImageUrl="Images/search.gif" runat="server" OnClick="cmdLkp_Click" />
</ContentTemplate>
</asp:UpdatePanel>
The code below in the code behind stopped working
protected void grdJobs_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Load")
{
functionToBindDataToGrid2();
functionToBindDataToOtherControls();
}
}
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", "javascript:__doPostBack('grdJobs$ctl" + ((Convert.ToInt32(e.Item.ItemIndex + 3).ToString("00"))) + "$ctl00','')");
}
In the properties for the UpdatePanel, set the update mode to "Conditional" and ChildrenAsTriggers to "true".
Another option would be to move the button inside the update panel so that you wouldn't have to have the trigger.
A GridView is a complex asp.net server control. You will have a lot of difficulty updating Grid2 after Grid1 is updated inside of the UpdatePanel. However, it is possible to a execute JavaScript on the client after Grid1 is updated. You could update Grid1 inside of the update panel, execute JavaScript after Grid1 has been updated that will update HTML on the page. The problem is that updating Grid2 with Javascript is going to be a nightmare amount of work.
Here's an example of what I'm talking about: Ajax Enabled Gridview using JavaScript in ASP.NET. It is a total hack, a huge amount of work, and your co-workers will hate you when they have to maintain it.
If you wanted to update a label or a dropdown list then that would be possible but updating a GridView using Javascript and having those updates persist across postbacks is a daunting challenge.
Use multiple UpdatePanels on one page. It won't affect the layout.
You can then use triggers (for the panels) in order to affect which controls you want affected.
Here's a page that will help you understand.
http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-updatepanel-triggers
Your problem is down to the way you are triggering the postback on row click, i.e.: this method
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", "javascript:__doPostBack('grdJobs$ctl" + ((Convert.ToInt32(e.Item.ItemIndex + 3).ToString("00"))) + "$ctl00','')");
}
Manually writing the __doPostBack script is generally always a bad idea. I believe what you need to use instead is ClientScriptManager.GetPostBackEventReference which will create a similar looking postback script for you, but will take into account all sorts of other things including AJAX-ification of the control.
Try something like this instead:
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", ClientScriptManager.GetPostBackEventReference(e.Item, string.Empty);
}

ASP.NET: Custom Control Reloads Whole Page

I'm working on a ASP.NET site with C# code.
Now the trouble starts when I create a custom control programmatically. The control displays in a panel, but when I click one of the buttons of the control it does nothing. If I click them twice, the user control disappears.
Using the debugger, I found that it's doing a postback, which is strange because I tried using buttons and setting the usesubmitbehavior to false; it's still sending postbacks.
Here is where the control is inserted on the default.aspx file
<asp:UpdatePanel runat="server" ID="contentHolderUpdatePanel"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel runat="server" ID="contentPanel">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Here is the ASPX from ListadoAuditoria of the control.
<asp:UpdatePanel runat="server" ID="auditorTableUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table runat="server" ID="auditorTable" BorderWidth="0" Width="100%">
<asp:TableHeaderRow HorizontalAlign="Center">
<asp:TableHeaderCell>Button
</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" ID="formHolderUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="testLabel" Text="bbbbbbbbbbbbb" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The method that the button invokes should change the text of the label testLabel from "bbbbbbbbbbbbb" to "aaaaaaaaaaa". Obviously I'm doing an auditorTableUpdatePanel.Update() after I modify the text.
The control CS
protected void Page_Load(object sender, EventArgs e)
{
loadAudits();
}
public void loadAudits()
{
for(int i=0;i<10;++i)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
ImageButton deleteButton = new ImageButton();
deleteButton.ImageUrl = "~/image.gif";
deleteButton.Click += generateNewPart;
deleteButton.EnableViewState = true;
deleteButton.ID = i.ToString();
cell1.Controls.Add(deleteButton);
row.Cells.Add(cell1);
auditorTable.Rows.Add(row);
}
}
public void generateNewPart(object sender, EventArgs e)
{
tumadre.Text = "aaaaaaaaaaaa";
formHolderUpdatePanel.Update();
}
And here is the code when I generate the control and insert it into the panel:
Panel panel = (Panel)Page.FindControl("contentPanel");
UpdatePanel updatePanel = (UpdatePanel)Page.FindControl("contentHolderUpdatePanel");
ListadoAuditorias listadoAuditorias = (ListadoAuditorias)LoadControl("~/CargaDeAuditoria/ListadoAuditorias.ascx");
panel.Controls.Add(listadoAuditorias);
updatePanel.Update();
I looked over the Internet and didn't found anything.
I'm not sure where exactly the code to dynamically add the controls is, but it must be called on EVERY postback to re-add the controls. You can't just add it once and forget about it. When you postback, the page will re-render with the markup in your aspx page (which does not have your dynamic controls, obviously). The values from the dynamically added controls will still be in ViewState, but the controls will not be re-rendered.
I'm not entirely sure what I'm looking at; I don't know if the "code of the control" is the code for the ListadoAuditorias control that you're loading. If so, I didn't notice any buttons.
So I could be wrong here, but the first thing that pops out at me is that it looks like you're loading the ListadoAuditorias control and then adding it to a normal Panel control. If one of the controls inside of ListadoAuditorias triggers a postback, and it's not contained within an UpdatePanel, then yes, I'd expect the page to do a postback and reload, unless you have specified the ChildrenAsTriggers and UpdateMode properties to be something other than their default values (I think). So I would just suggest that you take a look at where you are adding your controls. Make sure that they're contained within an UpdatePanel, if that's what your intention is.
Also, note that the UseSubmitBehavior property of the Button control does not prevent the button from initiating a postback. That property only determines whether the button gets rendered as <input type="submit" /> or <input type="button" />. In the latter case (when you set UseSubmitBehavior to false) the control still renders javascript in the HTML element's onclick attribute to cause a postback.
EDIT: I've amended my explanation regarding UpdatePanel control to mention the ChildrenAsTriggers and UpdateMode properties.

Categories

Resources