UpdatePanel sometimes refreshing entire page - asp.net

Even though I am using an update panel, sometimes my entire page is refreshed, and I can't figure out why.
(Edited to take into account Jason P's answer.)
Masterpage code:
<form runat="server" id="form1">
<asp:ScriptManager ID="ScriptManager1" runat="server" enablePartialRendering="true" />
<h1>Title</h1>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" childrenAsTriggers="true">
<ContentTemplate>
<ul class="letterLinks">
<asp:Repeater runat="server" ID="Letter_Repeater">
<ItemTemplate>
<li id='<%#Eval("Letter")%>'>
<asp:LinkButton runat="server" ID="UpdateLink" Text="My Text"
CommandName="BookLetter" CommandArgument='<%#Eval("Letter")%>' OnCommand="LoadBookTitles"/>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<ul class="BookList">
<asp:Repeater runat="server" ID="Title_Repeater">
<ItemTemplate>
<li><a href='<%#Eval("URL")%>'><%#Eval("Title")%></a></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Code Behind:
public partial class MyBooks : System.Web.UI.MasterPage
{
private GetAllBookInfo setMyInfo = new GetAllBookInfo();
private DataTable allTitleInfo = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
List<string> lettersWithBooks = new List<string>();
DataTable letterLinks = new DataTable();
// Get all letters that have Books
lettersWithBooks = setMyInfo.LettersWithBooks();
// get properties for ABC links
letterLinks = GetLetterLinkProperties(lettersWithBooks);
// Bind abc link data to the ABC repeater
Letter_Repeater.DataSource = letterLinks;
Letter_Repeater.DataBind();
allTitleInfo = setMyInfo.GetBookTitles(lettersWithBooks[0]);
// Bind title info data to title repeater
Title_Repeater.DataSource = allTitleInfo;
Title_Repeater.DataBind();
}
private DataTable GetLetterLinkProperties(List<string> letters)
{
DataTable letterLinks = new DataTable();
letterLinks.Columns.Add("Letter", typeof(string));
letterLinks.Columns.Add("Class", typeof(string));
letterLinks.Columns.Add("Enabled", typeof(bool));
for (char c = 'A'; c <= 'Z'; c++)
{
if (letters.Any(letter => letter == c.ToString()))
{
letterLinks.Rows.Add(c, "hasGuides", true);
}
else
{
letterLinks.Rows.Add(c, "noGuides", false);
}
}
return letterLinks;
protected void LoadBookTitles(object sender, EventArgs e)
{
LinkButton letterLink = (LinkButton)sender;
allTitleInfo = setMyInfo.GetBookTitles(letterLink.CommandArgument as String);
// Bind title info data to title repeater
Title_Repeater.DataSource = allTitleInfo;
Title_Repeater.DataBind();
}
}

Not sure if this is the entire problem, but the <Triggers> element should be on the same level as the <ContentTemplate> element, not a child:
<asp:UpdatePanel>
<Triggers>
...
<Triggers>
<ContentTemplate>
...
<ContentTemplate>
</asp:UpdatePanel>
Also, I believe in this case, the Repeater should be the trigger, not the LinkButton. Try removing the OnCommand event from the LinkButton and adding it to the Repeater, and changing the UpdatePanel's Trigger.

Related

Button inside UpdatePanel does not redirect me to another page

I have a form with a button that validates a required field and then if the validation is ok send me to another page. I have used AJAX with UpdatePanel that shows me a label if the field is required or not.
The problem is that when I press the button and the validation is correct it does not redirect me to another page.
<asp:UpdatePanel ID="upn_Data" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="row inp-row check-field">
<label for="option" class=" ">Option1 :*</label>
<div class="text-inp with-tooltip">
<asp:DropDownList ID="ddlOption1" runat="server" AutoPostBack="true" onselectedindexchanged="ddlOption1_SelectedIndexChanged">
</asp:DropDownList>
<asp:Label ID="lblRequiredOption1" runat="server" Text="Obligatory field" visible="false" AutoPostBack="true"></asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div id = "buttons" class ="buttons">
<asp:Button ID="Button1" runat="server" Text = "Continue" class="continue-btn" onclick="Button1_Click"></asp:Button>
</div>
</ContentTemplate>
</asp:UpdatePanel>
In server:
protected void Button1_Click(object sender, EventArgs e)
{
bool nextPage = true;
if (ddlOption1.SelectedValue == "*")
{
lblRequiredOption1.Visible = true;
nextPage = false;
}
if (nextPage == true) {
Type cstype = this.GetType();
String csName = "RedirectScript";
String script = "window.parent.location = '../Paso2.html'";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptBlock(cstype, csName, script.ToString(), true);
}
}

How to display records with time interval

I have a website i.e. I'm working on aspx pages. I am storing value in to the xml file.
I need to display value stored in xml at specified time interval (say 1 min) on a asp label. But not all records are to display at an instance. At first instance first record of xml and after time interval next record and so on. After last record again first record needed to display.
I Google search a lot on this but could not find specific solution on this.
Please help me with successful solution. Thanks...
This is my code but its not giving expected results. Please help me in editing this.
HTML code
<div>
<table width="100%">
<tr><td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</td></tr>
<tr><td>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
</asp:Timer>
</td></tr>
<tr><td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="" ></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
</td></tr>
<tr><td></td></tr>
</table>
</div>
ASPX coding
public partial class UpdateNews : System.Web.UI.Page
{
DataRow dr;
int i = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!ScriptManager1.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(120).ToString();
//GetNewValue();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
i++;
GetNewValue();
}
}
public void GetNewValue()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("News.xml"));
DataTable dt = ds.Tables[0];
if (i <= dt.Rows.Count)
{
dr = dt.Rows[i - 1];
Label1.Text = dr["Title"].ToString();
}
else
{
if(i > dt.Rows.Count )
i = 1;
}
}
}
You can use time with update panel in asp.net web forms.
Following is the code :
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<!-- your content here, no timer -->
</ContentTemplate>
Things you want to do can be put in timer1_tick
I got the answer now my code is running properly.
But now When I put my page in content page I get an new error :-(
Please help me I need to clear this error at its earliest due to my deadline.
It say: cannot implicitly convert type 'string' to 'system.web.ui.webcontrols.label' at line 1
Where line 1 is
<%# Page Language="C#" MasterPageFile="~/Main.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" Title="Untitled Page" %>
My working code is here :
HTML Code
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Title" runat="server" Text=""></asp:Label>
<asp:Label ID="News" runat="server" Text=""></asp:Label>
<asp:Label ID="Counter" runat="server" Text="" ></asp:Label>
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" /></Triggers>
</asp:UpdatePanel>
ASPX Code:
public partial class Home : System.Web.UI.Page
{
DataRow dr;
int i = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!ScriptManager1.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(100).ToString();
if (!string.IsNullOrEmpty(Counter.Text))
{
i = int.Parse(Counter.Text);
i++;
}
GetNewValue();
}
public void GetNewValue()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("News.xml"));
DataTable dt = ds.Tables[0];
if (i <= dt.Rows.Count)
{
dr = dt.Rows[i - 1];
Title.Text = dr["Title"].ToString();
News.Text = dr["Description"].ToString();
Counter.Text = i.ToString();
}
else
{
if (i > dt.Rows.Count)
i = 1;
Counter.Text = i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
GetNewValue();
}
}
}
My code was correct
Just error was I should not rename ID field of Labels in update panel.
I dont know why this happened.
But when I renamed my Title, counter,News label to label1 label2....
It worked properly and gave me my required result.
Thank you all for responding and trying to help me.

Firing ImageButton server side event but the page is not updating using ASP.NET UpdatePanel

I've feature to implement which is when user in the GridView footer and press on Enter key the row will be inserted. In the GridView I have 2 <asp:ImageButton> one in <EmptyDataTemplate> and the other in <FooterTemplate> I wrote JavaScript to execute the ImageButton Click event when use is in the last field, the ImageButton Server-Side Click event fired but the page is not updated.
Here is JavaScrip function:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
}
}
Here is the ASPX:
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
...
<asp:GridView ID="grvDonationDist" runat="server" AutoGenerateColumns="False" ShowFooter="True"
DataKeyNames="reciept_num,donation_code" meta:resourcekey="grvDonationDistResource1"
ShowHeaderWhenEmpty="True" BorderWidth="1px" BackColor="White" BorderColor="LightSteelBlue"
CellPadding="0" Font-Name="tahoma" Font-Size="10pt" ForeColor="DarkBlue" HeaderStyle-BackColor="#aaaadd"
GridLines="None">
<EmptyDataTemplate>
<asp:Label CssClass="label" ID="lblEmptyDonationDist" runat="server" Text="No Donations"
meta:resourcekey="lblEmptyDonationDistResource1"></asp:Label>
<tr>
<td>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAdd_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</td>
...
<td>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</td>
</tr>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField FooterText="Total" ShowHeader="False">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAddFromFooter_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Notes" SortExpression="distribution_remrks" meta:resourcekey="TemplateFieldResource3">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Here is VB.NET:
Protected Sub lbtnAddFromFooter_Click(sender As Object, e As EventArgs)
'Footer Add
'Add Insert Logic here
Try
Dim donationDist As New DonationDist
Dim txtDonationValueFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationValueFooter")
Dim txtDonationNotesFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationNotesFooter")
Dim ddlCountryFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlCountryFooter")
Dim ddlPurposeFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlNewDonationPurposeType")
Dim chkPartial As CheckBox = grvDonationDist.FooterRow.FindControl("chkPartialFooter")
Dim standInstruct As Label = grvDonationDist.FooterRow.FindControl("lblStandInstructFooter")
Dim donationValue As Decimal = Convert.ToDecimal(txtDonationValueFooter.Text)
'Validation: Donation Value must be > 0
If (donationValue <= 0) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("قيمة الترع يجب ان تكون أكبر من الصفر")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("Donation Value must be greater than 0")
End If
Exit Sub
End If
myDonationDistDataTable = Session("myDonationDistDataTable")
'Validation: Only one donation type per Receipt
For Each row As DataRow In myDonationDistDataTable.Rows
If (row.Item("donation_code") = ddlPurposeFooter.SelectedValue) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("لا يمكن تكرار الغرض في نفس سند القبض")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("You cannot add more than on Donation Type per receipt")
End If
Exit Sub
End If
Next
myDonationDistDataRow = myDonationDistDataTable.NewRow()
myDonationDistDataRow("reciept_num") = 0
myDonationDistDataRow("donation_code") = Convert.ToInt16(ddlPurposeFooter.SelectedValue)
myDonationDistDataRow("donation_name") = ddlPurposeFooter.SelectedItem.Text
myDonationDistDataRow("donation_value") = Convert.ToDecimal(txtDonationValueFooter.Text)
myDonationDistDataRow("country_code") = Convert.ToInt16(ddlCountryFooter.SelectedValue)
myDonationDistDataRow("country_name") = ddlCountryFooter.SelectedItem.Text
myDonationDistDataRow("distribution_remrks") = txtDonationNotesFooter.Text
myDonationDistDataRow("partial") = chkPartial.Checked
myDonationDistDataRow("standing_inst_num") = If(String.IsNullOrWhiteSpace(standInstruct.Text), 0, Convert.ToInt32(standInstruct.Text))
'add the new DataRow to DataTable's Row
myDonationDistDataTable.Rows.Add(myDonationDistDataRow)
Session("myDonationDistDataTable") = myDonationDistDataTable
grvDonationDist.DataSource = myDonationDistDataTable
grvDonationDist.DataBind()
Catch ex As Exception
'TODO: Log the exception
End Try
End Sub
What is wrong with this code? Am I missing something?
you can't do it that way, you will need to add the event to the update panel
javascript:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
__doPostBack('<%= UpdatePanel.UniqueId %>', '');
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional" onload="UpdatePanel_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
CS:
protected void UpdatePanel_Load(object sender, EventArgs e)
{
//add your code here
}
if you do not get the _doPostBack in your code you can add it like this..
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);
}
I solve it just by add return false after the insertByEnterKey() function
onKeyDown="insertByEnterKey('lbtnAdd'); return false;"
Even better solution:
Make the JavaScript Function return False when the user press "Enter Key" otherwise return True.
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
return false;
} else {
return true;
}
}
and use it in the Textbox like this:
<asp:TextBox ID="txtDonationNotesFooter" runat="server" onKeyDown="return insertByEnterKey('lbtnAdd');"></asp:TextBox>

Asp.Net ListView's Items property is always empty

Good day
I have a user control that contains a ListView which is being used to display tabs.
I am databinding the ListView and on the OnItemDataBound event adding the tab elements.
However the Items property never contains anything and is always empty (on PostBack and on ItemDataBound).
Markup:
<asp:ListView ID="SaleTabsListView" runat="server" OnItemDataBound="SaleTabsListView_OnItemDataBound" ItemPlaceholderID="SaleTabsPlaceHolder" EnableViewState="true">
<LayoutTemplate>
<div class="tabs">
<asp:PlaceHolder runat="server" ID="SaleTabsPlaceHolder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="ItemPlaceHolder" />
</ItemTemplate>
</asp:ListView>
Code behind:
protected void SaleTabsListView_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var saleTab = ((ListViewDataItem)e.Item).DataItem as SalesTab;
if (saleTab != null)
{
var placeHolder = e.Item.FindControl("ItemPlaceHolder") as PlaceHolder;
var htmlAnchor = new HtmlAnchor();
htmlAnchor.Attributes.Add("id", saleTab.Id);
htmlAnchor.Attributes.Add("class", saleTab.IsCurrent ? currentTabClass : string.Empty);
var emptyLabel = new Label();
var label = new Label {Text = saleTab.Title};
label.Attributes.Add("id", saleTab.Id + "Label");
label.Attributes.Add("class", saleTab.IsComplete ? completeClass : incompleteClass);
emptyLabel.Controls.Add(label);
htmlAnchor.Controls.Add(emptyLabel);
placeHolder.Controls.Add(htmlAnchor);
}
}
}
So my question is: is the binding I'm doing somehow screwing with the Items property?
Thanks

Working with Datalist in asp.net?

good morning to all.
i place a datalist in my project in that i place a link button when i click on that link button a panel will open in that row with a textbox and a button. it is working fine but my problem is if i click on one link button of a row panel will open, when i click on second row link button the sencond row panel is opening but first row panel is not closing. I think you get my point owhter wise i will explain again this is my code check out
<form id="form1" runat="server">
<div>
<asp:DataList ID="Mydatalist" runat ="Server"
OnItemCommand="Mydatalist_ItemCommand" >
<ItemTemplate >
<table >
<tr>
<td>
<asp:Label ID="lblcouname" runat ="server"
Text ='<%# Eval("country_name") %>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="lnkrepl" Text="reply"
CommandName ="reply" runat ="server"
CommandArgument ='<%# Eval("country_id") %>'>
</asp:LinkButton>
</td>
</tr>
</table>
<div>
<asp:Panel ID="mypane" runat ="Server" Visible ="false" >
<asp:TextBox ID="txtpane" runat ="Server" ></asp:TextBox><br />
<asp:Button ID="btnInsert" runat="Server" Text ="Insert" />
</asp:Panel>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
Code behind:
public partial class Datlist : System.Web.UI.Page
{
SqlConnection con; SqlDataAdapter da; DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(
#"server=msmsm;database=pop;user id=sa;password=abc");
con.Open();
if (!IsPostBack)
{
getCountry();
}
}
public void getCountry()
{
string sqr="select * from country";
da=new SqlDataAdapter (sqr,con);
ds = new DataSet();
da.Fill(ds,"country");
Mydatalist.DataSource = ds.Tables[0];
Mydatalist.DataBind();
}
protected void Mydatalist_ItemCommand(object source, DataListCommandEventArgs e)
{
Panel pn = (Panel)e.Item.FindControl("mypane");
pn.Visible = false;
if (e.CommandName == "reply")
{
pn.Visible = true;
}
}
}
You have to programmably hide it. THe DataList should have an items property, and as such you can loop through all items, find the panel control using FIndControl, and set its visibility to false.
EDIT: So you need to do:
private void HideItems()
{
foreach (var item in this.dl.Items)
{
var panel = item.FindControl("mypane") as Panel;
if (panel != null)
panel.Visible = false;
}
}
In ItemCommand, call this method to hide all the existing control's panels.

Resources