Textbox focus in asp updatepanel - Working with breakpoint but not without - c#

I'm having a really strange problem where my code works with a breakpoint set in the code, but when I remove the breakpoint, parts of the code stop functioning.
I'm trying to make a textbox select all text on focus; I want it to automatically focus, selecting all text, when a search is performed.
I have a texbox (groupSearchTextbox), button (groupSearchButton), and a listbox which is inside of an update panel, inside of a panel with a default button specified:
<asp:Panel ID="groupPanel" runat="server" CssClass="listContainer" DefaultButton="groupSearchButton">
<h2>User Groups</h2>
<div class="searches">
<asp:TextBox ID="groupSearchTextbox" runat="server"></asp:TextBox>
<asp:Button ID="groupSearchButton" runat="server" Text="Search" OnClick="groupSearchButton_Click" />
<asp:Button ID="showAllGroupsButton" runat="server" Text="Show All" OnClick="showAllGroupsButton_Click" CssClass="right" />
</div>
<asp:UpdatePanel ID="groupUpdate" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:ListBox ID="groupListbox" runat="server" CssClass="list"></asp:ListBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="groupSearchButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="showAllGroupsButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
I also have a jquery function to make the textboxes select on focus:
$('.searches input[type=text]').focus(function () {
$(this).select();
});
and onclick of groupSearchButton I have the following function to remove items from the listbox if they are not results of a search, and focus on the textbox:
protected void groupSearchButton_Click(object sender, EventArgs e) {
fillGroups(); //Sets the listbox to the original list
string searchString = groupSearchTextbox.Text;`
for (int i = groupListbox.Items.Count - 1; i > 0; i--) {
string itemName = groupListbox.Items[i].ToString();
if (!itemName.ToLower().Contains(searchString.ToLower())) {
groupListbox.Items.Remove(groupListbox.Items[i]);
}
}
groupSearchTextbox.Focus();
}
When I click the groupSearchButton, everything works as expected. I get my results and the groupSearchTextbox gets focus with the text selected.
When I press enter while focused on the textbox, making use of the panel's default button attribute, I get my results but the text in the textbox is not selected.
The strange part is, if I put a breakpoint where I set the focus in the groupSearchButton_Click method, the above method of pressing enter in the textbox works properly and the text is selected.
Any ideas what might be going on here?
Edit:
So I'm pretty sure that the issue is that the textbox needs to lose focus in order for it to select the text when it focuses again. That would explain the actual clicking of the button working, as well as (I believe) the breakpoint issue, since the textbox would lose focus when Visual Studio is displayed.
I came up with a fairly hacky jquery fix for this, but would still love to know if there's a decent way to handle this properly

If you want to focus on only one text box then you can use
<asp:Panel ID="groupPanel" runat="server" CssClass="listContainer" DefaultButton="groupSearchButton" defaultfocus="groupSearchTextbox">
on your panel

You can use this in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
groupSearchTextbox.Focus();
}
}

Related

asp:listbox, don't autopostback until clicked outside

this might seem like kind of a weird request, but I'm looking to prevent autopostback for selected index change until the user clicks outside of the listbox, instead of when the user selects/deselects an item.
Is such a thing possible? The reason I ask is I have the following plug in used for a multiselect dropdown.
As it is right now, autopostback closes the dropdown each time a user select an item, and the index is successfully changed. However, if I turn autopostback off, it stays open to allow the user to select multiple items, but it won't register as selected.
If anyone could suggest a means of doing this I would be eternally grateful. Thanks so much in advance.
I'll post my asp.net and c# codebehind for the multiselect below.
ASP.NET
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:ListBox ID="DependenciesListBox" runat="server" SelectionMode="Multiple" Width="300px" CssClass="search-box-sel-all" multiple="multiple" placeholder="Select Child Dependencies" ToolTip="Items that depend on this currency item" AutoPostBack="True" OnSelectedIndexChanged="DependenciesListBox_SelectedIndexChanged"></asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
C#
protected void DependenciesListBox_SelectedIndexChanged(object sender, EventArgs e) {
ChildLabel.Text = "";
foreach (ListItem item in DependenciesListBox.Items) {
if (item.Selected)
ChildLabel.Text += item.ToString() + ", ";
}
}
<asp:ListBox ID="DependenciesListBox" runat="server" SelectionMode="Multiple" Width="300px" CssClass="search-box-sel-all" multiple="multiple" placeholder="Select Child Dependencies" ToolTip="Items that depend on this currency item" AutoPostBack="False" onchange="clientListChanged(this);" OnSelectedIndexChanged="DependenciesListBox_SelectedIndexChanged"></asp:ListBox>
//Java script code
function clientListChanged(el)
{
if ( el.value == '1' ) // for all indexes you dont want to post back add condition
{
return false;
}
return true; //else postback
}
Use onblur event for the event when user clicks outside the box and do a post back. I'm not sure if it allows html markup with list box; if not add via code behind using attributes.add for the list box. Then you can probably use __doPostBack(elementName.ClientId) in asp quotes to post to server
Note: I have not tested the code for errors or syntax issues. I just wrote it down here in editor. So please fix any errors you find.
I don't know perfect answer,
But this works for me, i hope it will work for you
Use updatepanel triggers
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="DependenciesListBox"
EventName="SelectedIndexChanged
="SelectedIndexChanged" />
</Triggers>

Hide div on textbox change without AutoPostBack

I have a textbox that users can enter comments into, and then click save. When they click save, some code executes in the background, but their comments stay in the textbox so that they can see them. I want to display some text above the box that says "Comments saved" when they click save, so that they know that their request went through, since nothing else changes on the page after clicking save. However, they can then change the text in the textbox, and it won't save unless they click "save" again. So, I want the "Comments saved" text to disappear if they change the text in the box. However, I cannot set AutoPostBack="true", because it will mess up some other stuff that's happening on the page. Is there a way to make the "Comments Saved" text disappear when the textbox is changed, without reloading the page? Here is the code I have so far:
<div id="savedMsg" runat="server"><p class="msgAlert"> Comments Saved! </p></div>
<div>
<asp:Panel runat="server" DefaultButton="Save">
<asp:TextBox runat="server" ID="TextBox" CssClass="form-control" TextMode="MultiLine"/>
</asp:Panel>
</div>
Here is the code behind:
protected void SaveComments(object sender, EventArgs e)
{
//some code here that is unrelated
savedMsg.Visible = true;
}
Ideally, I would set TextChange="SomeMethod" and include this in my code behind:
protected void SomeMethod(object sender, EventArgs e)
{
savedMsg.Visible = false;
}
but I can't enable AutoPostBack, so this event never happens.
You can hide the message on the onkeydown event of the TextBox:
<asp:TextBox runat="server" ID="TextBox" onkeydown="hideSaveMessage();" CssClass="form-control" TextMode="MultiLine" />
with the Javascript code:
<script type="text/javascript">
function hideSaveMessage() {
var div = document.getElementById('<%= savedMsg.ClientID %>');
div.style.visibility = 'hidden';
}
</script>
You could also use div.style.display = 'none' to hide the message but that causes the TextBox to "jump" to a new position, which is somewhat disturbing.
I used document.getElementById('<%= savedMsg.ClientID %>') to account for any modification applied to the div ID by ASP.NET. The simpler syntax document.getElementById('savedMsg') may work in your case.

Set Visibility of Panel Inside Update Panel From Code behind From An Update Panel

I have simplified and probably made a typo or two below, but I am trying to show and hide the visibility of pnl2, this code however doesn't work. I thought as long as the panel was in another update panel I can control visibility.
Oddly enough if I debug this in Visual studio, and F10 all the way through it, it shows the visibility correctly, but when I hit my Last F10 and the page loads, it's always incorrect.
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPanel1">
<ContentTemplate>
<asp:Panel runat="Server" ID="pnl1"/>
<asp:Button runat="Server" ID="hidePanel2" OnClick="HidePanel2"/>
</ContentTemplate>
</UpdatePanel>
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPanel2">
<ContentTemplate>
<asp:Panel runat="Server" ID="pnl2"/>
</ContentTemplate>
</UpdatePanel>
protected void hidePanel2(object sender, EventArgs e)
{
if (pnl2.Visible == true)
{
pnl2.Visible = false;
}else
{
pnl2.Visible = true;)
}
The problem is that you are trying to update the visibility of “pnl2” from a button that is in the UpdatePanel named “updPanel1”. The postback for the button “hidePanel2” only causes the content of update panel “updPanel1” to change. The rest of the form, including update panel “updPanel2”, does not change.
The most direct solution, if the two panels are next to each other, is to put them both in one update panel. If you have some other layout then you will need to explain what it is before we can help.

ASP.NET Ajax History not working correctly

I have an ASP.NET/C# application.
The application containsa PlaceHolder inside an UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LinkButton1" EventName="Click"/>
<asp:AsyncPostBackTrigger ControlID="LinkButton2" EventName="Click"/>
<asp:AsyncPostBackTrigger ControlID="LinkButton3" EventName="Click"/>
</Triggers>
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
</asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Basically I load controls in the placeholder depending on what LinkButton has been clicked using a function
LoadControls("ControlName");
I want to implement the ability for the user to use the Browser Back Button
in order to navigate through the controls. so I used AJAX History like this:
I save the current control ID in a session variable
Session["current"]
I enable History in scriptmanager and add an event handler
<asp:ScriptManager ID="ScriptManager" runat="server" EnableHistory="True" onnavigate="ScriptManager_Navigate" />
(The event handler will be covered below)
First I will create a new history point in the event handler of the Linkbuttons (they all use the same handler)
string ControlId=Session["current"].ToString();
if (ScriptManager.IsInAsyncPostBack && !ScriptManager.IsNavigating)
{
ScriptManager.AddHistoryPoint("Hist", ControlId);
}
then in the Scriptmanager navigate handler
protected void ScriptManager_Navigate(object sender, HistoryEventArgs e)
{
string Controlid = "";
if (e.State["index"] != null)
{
Controlid = e.State["Hist"].ToString();
LoadControls(Controlid );
}
}
When I load the controls I can navigate back and forward and everything is working fine
Here is the problem:
1) first problem
The first time I click on "Back". the history returns 2 steps and not one (after that it works normaly.) It is like the last history is not saved.
2) second problem
After "Backing" to the first step I can do an extra "Back" where the e.State["Hist"] will be null and give me an error. how can I disable the "Browser Back" button when the e.State["Hist"] will be null?
Thank you very much for any help. I hope I was clear.
If you need more info/code I will gladly provide them
Never mind. it was just a bug. the Session["Current"] was saving the previous control and not the current one. It is now fixed. I will leave this question if somebody needs a small example for creating ajax history.

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