Update panel automatically clears textboxes - asp.net

I'm trying to combine an event of automatic printing of messages in case the passwords will not match. For that purpose I'm using an Update panel.
The Error message prints perfectly My problem is that both text-boxes automatically created after it. even thought I don't specify it in the code. I can't understand what have I done wrong.
This is the code for front end:
<asp:TextBox ID="NonPass1" runat="server" TextMode="Password"></asp:TextBox>
<asp:TextBox ID="NonPass2" runat="server" TextMode="Password" autopostback="True"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel6" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel6" runat="server">
<asp:Label ID="Label1" class="errorMess" runat="server" Text="The Passwords do not match!!!"></asp:Label>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="NonPass2" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
this is the back end code(I'm using VB):
Protected Sub NonPass2_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles NonPass2.TextChanged
If NonPass1.Text <> NonPass2.Text Then
Panel3.Visible = False
Panel6.Visible = True
Else
Panel3.Visible = False
Panel6.Visible = False
End If
End Sub

maybe you can use javascript functions.
<script>
var t1 = false; // textbox1 onfocus triggered = true;
var t2 = false; // textbox2 onfocus triggered = true;
function clearTBox() {
if (t1 && t2) {
if (document.getElementById("textbox1Name").value != document.getElementById("textbox1Name2").value) {
alert("Insert your code here");
}
}
}
</script>

Heres what i use in c# for this, maybe you can inherit the technique
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
then call cleartextboxes();
Hope that helped :)

what do you mean :
My problem is that both text-boxes automatically created after it
please, make your question more clearance
Try not to use updatepanel,
try this
<asp:TextBox ID="NonPass1" runat="server" TextMode="Password"></asp:TextBox>
<asp:TextBox ID="NonPass2" runat="server" TextMode="Password" autopostback="True"></asp:TextBox>
<div id="Div_Error" runat="server" visible="false" style="width:100%">
<asp:Label ID="Label1" class="errorMess" runat="server" Text="The Passwords do not match!!!"></asp:Label>
and use this in the code behind:
Protected Sub NonPass2_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles NonPass2.TextChanged
If NonPass1.Text <> NonPass2.Text Then
Div_Error.visible=true;
Else
Div_Error.visible=false;
End If
End Sub

The only logical reason for the behavior as you described is perhaps, you put the above password boxes inside another UpdatePanel.
Therefore, the password boxes will be reloaded on postbacks (textchanged event), and TextBox of type Password do not retain its value after postbacks for security reason.
Though, if security is not a concern for you, there is a workaround to 'avoid' the password textboxes from being cleared on postbacks, by reassigning their values every time postbacks occur. Just include the following codes in the page Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
NonPass1.Attributes.Add("value", NonPass1.Text)
NonPass2.Attributes.Add("value", NonPass2.Text)
End Sub

this is a simple example:
<table class="mytable" cellspacing="0" style="width: 100%">
<tr>
<td>
<asp:TextBox ID="Txt_Pass" runat="server" ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="Txt_Re_Pass" runat="server" ></asp:TextBox>
</td>
<td width="66%" align="left">
<asp:Button ID="Btn_Filter" runat="server" Text="" Height="22px" />
</td>
</tr>
</table>
<br />
<div id="Div_Error" runat="server" visible="false" style="width:100%">
<asp:Label ID="lbl_Error" runat="server" class="msg">
</asp:Label>
</div>
and in the code behind , use this:
Protected Sub Btn_Filter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btn_Filter.Click
If Trim(Txt_Re_Pass.Text) <> "" Then
Div_Error.Visible = False
if Txt_Pass.Text <> Txt_Re_Pass.Text then
Div_Error.Visible = True
lbl_Error.text="The Passwords do not match!!!""
else
Div_Error.Visible = False
End if
Else
Div_Error.Visible = True
lbl_Error.text="Please re enter your password"
End If
End Sub

Related

ItemCommand of DataList in UpdatePanel is not fired on Postback

I have a popup panel which contains an UpdatePanel, which contains a DataList. Table rows are populated using ItemTemplate and there is a LinkButton generated on each row for deleting this row. I would like to delete this record in the DataList's ItemCommand event handler and rebind the DataList.
However, after I click a "delete" button in the DataList, ItemCommand is not fired. I've already checked if IsPostBack in my Page_Load and only do Datalist.Databind() if it's not a postback. Normally I would expect first Page_Load and then list_ItemCommand being called after I click a delete button in the DataList, but list_ItemCommand is not called as expected. And nothing is then displayed in DataList which is inside the UpdatePanel.
And stranger, if I remove the IsPostBack check in Page_Load, that being said, rebind the DataList in every Page_Load, ItemCommand will be caught and list_ItemCommand is called. This is against the answers in many other posts "ItemCommand event will be canceled if DataList is rebinded during PostBack".
Code behind:
Protected records As New List(Of Record)
Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Set some page properties...
If Not Page.IsPostBack Then
GetListOfRecordFromDatabase()
datalist.DataSource = records
datalist.DataBind()
End If
End Sub
Protected Sub datalist_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles datalist.ItemCommand
Select Case e.CommandName.ToLower
Case "delete"
For Each c As Record In records
If c.Id = e.CommandArgument Then
records.Remove(c)
Exit For
End If
Next
DeleteRecordFromDatabase(e.CommandArgument)
datalist.DataSource = records
datalist.DataBind()
End Select
End Sub
Controls:
<asp:Content ID="content1" runat="server" ContentPlaceHolderID="Content1PlaceHolder">
<asp:LinkButton ID="btnpopup" runat="server" OnClientClick="javascript:return popup()"></asp:LinkButton>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" EnableViewState="false" >
</asp:ScriptManagerProxy>
<asp:Panel ID="PanelPopup" runat="server" style="display:none;">
<asp:UpdatePanel ID="UPPopup" runat="server" UpdateMode="conditional" EnableViewState="false">
<ContentTemplate>
<div id="divPopup1" runat="server">
<table id="table1" cellpadding="2" cellspacing="1" width="500" border="0" >
<asp:DataList ID="datalist" runat="server" OnItemCommand="datalist_ItemCommand">
<ItemTemplate>
<tr align="center">
<td><%#Container.ItemIndex +1 %></td>
<td><asp:Label ID="Label1" runat="server" Text='<%# eval("Name") %>'></asp:Label></td>
<td><asp:Label ID="Label2" runat="server" Text='<%# eval("Color") %>'></asp:Label></td>
<td><asp:LinkButton ID="Delete" CommandName="Delete" runat="server" Text="Delete" CommandArgument='<%# eval("Id") %>' ></asp:LinkButton></td>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div style="text-align:center;"><br />
<asp:Button ID="BtnSavePopup" runat="server" Text="Save and Close"/>
</div>
</asp:Panel>
<script type="text/javascript">
function popup() {
return mypagehelper.openAsModalPopup("<% =PanelPopup.ClientID%>");
}
</script>
</asp:Content>
Further more, I tried to grab the ControlID and the Control who raised the event during Postback using this code:
If IsPostBack Then
Dim CtrlID As String = String.Empty
If Request.Form("__EVENTTARGET") IsNot Nothing And
Request.Form("__EVENTTARGET") <> String.Empty Then
CtrlID = Request.Form("__EVENTTARGET")
Dim postbackControl As System.Web.UI.Control = Page.FindControl(CtrlID)
Else
End If
And I found that I can get my CtrlID as "ctl00$datalist$ctl08$Delete" but the postbackControl is Nothing. While on my other normal pages I can get both the controlID and actual control(which is a LinkButton) who raised the event.
Remove EnableViewState="false" from update panel.
it's late answer but i faced in soon, also may be it help some one else ...
the CommandName="Delete" is reserved for DataList "OnItemDeleting" Event
so just changing the CommandName to anything else (for example "Remove") will help or handle the OnItemDeleting Event.

TextBox TextChange event is not working in vb.net

I am using asp textbox control with TextChange event, trying to set the text to label as the textbox text get changed but it is working when i loose the focus from textbox not when text changes.
the problem with loosing focus is that if i use AutoPostBack="true" it refresh the page which affects my other values...
my source for textbox on aspx page
<asp:TextBox ID="txtSearchCust" runat="server" Width = "200" OnTextChanged="txtSearchCust_TextChanged" AutoPostBack="true" />
my code behind page source
Protected Sub txtSearchCust_TextChanged(sender As Object, e As EventArgs) Handles txtSearchCust.TextChanged
QtyChk.Text=txtSearchCust.Text
End Sub
here QtyChk is the label where I am trying to set the text
any solution...?
Based on your question.
<script type="text/javascript">
function doTextBoxChange() {
__doPostBack();
}
</script>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" onkeydown="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack() Then
LabelChange()
End If
End Sub
Sub LabelChange()
Label1.Text = "1234"
End Sub
But I think use javascript is a better option.
The values will disappear after post, you need to request the value and setup.
otherwise, use viewstate or session.
Using the javascript, don't post form data.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
function doTextBoxChange() {
var inputValue = document.getElementById("TextBox1").value;
document.getElementById('<%= Label1.ClientID %>').innerHTML = inputValue;
}

General Function

in a project I am working on I have TabContainer (AJAX.NET) have many tabPanels all of them are doing the same function BUT each on on a different Table
let me give a sample :
<asp:TabContainer ID="TabContainer3" runat="server" ActiveTabIndex="0" BorderStyle="None"
BorderWidth="0" CssClass="MyTabStyle" Width="625px">
<asp:TabPanel ID="TabPanel1" runat="server">
<HeaderTemplate>
Tab_x
</HeaderTemplate>
<ContentTemplate>
<asp:TextBox ID="txt_x" runat="server"></asp:TextBox>
<asp:Button ID="btnx" runat="server" Text="Button" />
</ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="TabPanel2" runat="server">
<HeaderTemplate>
Tab_y
</HeaderTemplate>
<ContentTemplate>
<asp:TextBox ID="txt_y" runat="server"></asp:TextBox>
<asp:Button ID="btny" runat="server" Text="Button" />
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
Code behind (VB.NET)
Protected Sub btnx_Click(sender As Object, e As System.EventArgs) Handles btnx.Click
SaveText_x(txt_x.Text)
End Sub
Protected Sub btny_Click(sender As Object, e As System.EventArgs) Handles btny.Click
SaveText_y(txt_y.Text)
End Sub
is there a way to create general Sub or Function so if I clicked btnx function Save_x(txt_x.Text) be called
and when I click btny function Save_y(txt_y.Text) be called ?
You can assign multiple buttons to have the same click handler with the following code :
Protected Sub btn_Click(sender As Object, e As System.EventArgs) Handles btnx.Click, btny.Click
Dim btn As Button = CType(sender, Button)
If btn.ID = "btnx" Then
SaveText_x(txt_x.Text)
ElseIf btn.ID = "btny" Then
SaveText_y(txt_y.Text)
End If
End Sub
Both btnx and btny will both fire this Sub and it will check the button that sent it to see which method to call.
1)Made user control with public string property. use view state to store value of that property.
2)Add that user control into your tabs set that property with values like "X" or "Y" or any.
3)On button click check that property with if .. else if .. else or by switch statement and call your SaveText functions variants.

How to add asyncPostBackTrigger to Template column, Item Template, Button in DataGrid

I need to add a trigger for two buttons in DataGrid Template columns. I have found a couple postings saying to put the code in the code-behind using the UniqueID.
Something isn't right with my logic (or maybe it isn't in the right place). I am getting "Object reference not set to an instance of an object" error when I run it.
I am getting this on my "gridSelectTrigger.ControlID = btnSessionSelect.UniqueID" statement.
Does this logic need to be in an "ItemDataBound" event? Or is my logic wrong?
<%# Page Title="Admin Session Folders" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="AdminAddEditReleaseAndFiles.aspx.vb" Inherits="AdminAddEditReleaseAndFiles" Theme="Standard" %>
<asp:Panel ID="pnlEditTopic" runat="server" CssClass="modalPopupEditTopic" Style="display: none;" >
<table cellspacing="0" class="borderTable0" width="100%" style="">
<tr style="height:4px">
<td colspan="6" align="center">
<asp:ImageButton ID="btnAddTopic" runat="server" AlternateText="Add Topic"
ImageUrl="~/App_Themes/Common/images/BtnApply.jpg" Height="28px">
</asp:ImageButton>
<asp:ImageButton ID="btnUpdateTopic" runat="server" AlternateText="Update Topic"
ImageUrl="~/App_Themes/Common/images/BtnApply.jpg" Height="28px">
</asp:ImageButton>
<asp:ImageButton ID="btnDeleteTopic" runat="server" AlternateText="Delete Topic"
ImageUrl="~/App_Themes/Common/images/BtnDelete.jpg" Height="28px">
</asp:ImageButton>
<asp:ImageButton ID="btnEditTopicClose" runat="server" AlternateText="Close Edit Topic Popup"
ImageUrl="~/App_Themes/Common/images/BtnCancel.jpg" Height="28px">
</asp:ImageButton>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not (IsPostBack) Then
Dim MainContent As ContentPlaceHolder = TryCast(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
Dim UpdatePanelSessions As UpdatePanel = TryCast(MainContent.FindControl("UpdatePanelSessions"), UpdatePanel)
Dim btnSessionSelect As Button = TryCast(UpdatePanelSessions.FindControl("btnSessionSelect"), Button)
Dim btnSessionDetail As Button = TryCast(UpdatePanelSessions.FindControl("btnSessionDetail"), Button)
Dim gridSelectTrigger As AsyncPostBackTrigger = New AsyncPostBackTrigger
Dim gridDetailTrigger As AsyncPostBackTrigger = New AsyncPostBackTrigger
gridSelectTrigger.ControlID = btnSessionSelect.UniqueID
gridSelectTrigger.EventName = "Click"
UpdatePanelSessions.Triggers.Add(gridSelectTrigger)
gridDetailTrigger.ControlID = btnSessionDetail.UniqueID
gridDetailTrigger.EventName = "Click"
UpdatePanelSessions.Triggers.Add(gridDetailTrigger)
End If
End Sub
Thank you,
James
Got it. The update panel needed children as triggers set to true.

How do I best populate an HTML table in ASP.NET?

This is what I've got. It works. But, is there a simpler or better way?
ASPX Page…
<asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
ASPX.VB Code Behind…
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return " "
Else
Return s
End If
End Function
#Geoff
That sort of Eval statement was actually added in 2.0, but if performance is important Eval should be avoided since it uses Reflection.
The repeater is a pretty good way of doing it, although it might be faster to generate the table in code:
ASPX Page:
<table class="report" id="bookTable" runat="server">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</table>
Code Behind:
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostback Then
BuildTable()
End If
End Sub
Private Sub BuildTable()
Dim db As New BookstoreDataContext
Dim bookCollection = from b in db.Books _
Order By b.Published _
Select b
Dim row As HtmlTableRow
Dim cell As HtmlTableCell
For Each book As Books In bookCollection
row = New HtmlTableRow()
cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = Format(b.Price, "c") }
row.Controls.Add(cell)
bookTable.Controls.Add(row)
Next
I guess it depends on how important speed is to you. For simplicity's sake I think I would go with the Repeater.
The ListView control introduced with framework 3.5 might be a little bit better solution. Your markup would look like this:
<asp:ListView runat="server" ID="ListView1"
DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id="table1" runat="server" >
<tr runat="server" id="itemPlaceholder" ></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td runat="server">
<asp:Label ID="NameLabel" runat="server"
Text='<%#Eval("Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
You'll want to set your data source ID from a public or private property in the code-behind class.
In .Net 3.0+ you can replace your ItemDataBound to the asp:Literal by doing something like this:
<ItemTemplate>
<tr>
<td><%# Eval("published") %></td>
...
where "published" is the name of a field in the data you have bound to the repeater
Edit:
#Alassek: I think the performance hit of reflection is often over-emphasized. Obviously you need to benchmark performance of your app, but the hit of the Eval is likely measured in milliseconds. Unless your app is serving many concurrent hits, this probably isn't an issue, and the simplicity of the code using Eval, along with it being a good separation of the presentation, make it a good solution.
This is what the GridView is for.
<asp:GridView runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField HeaderText="Published" DataField="Published" />
<asp:BoundField HeaderText="Author" DataField="Author" />
</Columns>
</asp:GridView>
I would use a GridView (or DataGrid, if you are using an older version of ASP.NET).
<asp:GridView ID="gvBooks" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Published" DataField="Published" />
<asp:BoundField HeaderText="Title" DataField="Title" />
<asp:BoundField HeaderText="Author" DataField="Author" />
<asp:BoundField HeaderText="Price" DataField="Price" />
</Columns>
</asp:GridView>
With some code-behind:
Private Sub gvBooksRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBooks.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
''' Your code here '''
End Select
End Sub
You can bind it in a similar way. The RowDataBound event is what you need.
I agree with Geoff, the only time we use Literals is if we want to do something different with the data.
For example, we might want a DueDate field to say "Today" or "Yesterday" instead of the actual date.
ALassek wrote:
…generate the table in code…
I like the look of that! It seems MUCH less likely to produce a run-time exception due to a typo or field name change.
If you don't need ASP.NET handled edit cabilities I would stay away from the DataGrid and the GridView ... they provide unnecessary bloat.

Resources