I want to prevent ASP.NET GridView from reacting to the enter button - asp.net-2.0

I have an ASP.NET page with a gridview control on it with a CommandButton column with delete and select commands active.
Pressing the enter key causes the first command button in the gridview to fire, which deletes a row. I don't want this to happen. Can I change the gridview control in a way that it does not react anymore to pressing the enter key?
There is a textbox and button on the screen as well. They don't need to be responsive to hitting enter, but you must be able to fill in the textbox. Currently we popup a confirmation dialog to prevent accidental deletes, but we need something better than this.
This is the markup for the gridview, as you can see it's inside an asp.net updatepanel (i forgot to mention that, sorry): (I left out most columns and the formatting)
<asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFilter" />
<asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="CodeGrid" class="Grid">
<asp:GridView ID="dgCode" runat="server">
<Columns>
<asp:CommandField SelectImageUrl="~/Images/Select.GIF"
ShowSelectButton="True"
ButtonType="Image"
CancelText=""
EditText=""
InsertText=""
NewText=""
UpdateText=""
DeleteImageUrl="~/Images/Delete.GIF"
ShowDeleteButton="True" />
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>

Every once in a while I get goofy issues like this too... but usually I just implement a quick hack, and move on :)
myGridView.Attributes.Add("onkeydown", "if(event.keyCode==13)return false;");
Something like that should work.

This solution is blocking the enter key on the entire page
Disable Enter Key

In the PreRender event you can toggle
Private Sub gvSerials_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvSerials.PreRender
If gvSerials.EditIndex < 0 'READ ONLY MODE
'Enables the form submit during Read mode on my 'search' submit button
Me.bnSearch.UseSubmitBehavior = True
Else 'EDIT MODE
'disables the form submit during edit mode, this allows the APPLY/Update button to be activated after Enter Key is pressed (which really is creating a form submit)
Me.bnSearch.UseSubmitBehavior = False
End If

In Page_Load, set the focus on the textbox.

Here is a good jQuery way of doing it. This function will automagically add the keydown event handler to all TextBoxes on the page. By using different selectors, you can control it to more or less granular levels:
//jQuery document ready function – fires when document structure loads
$(document).ready(function() {
//Find all input controls of type text and bind the given
//function to them
$(":text").keydown(function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
This will make all textboxes ignore the Enter key and has the advantage of being automatically applied to any new HTML or ASP.Net controls that you might add to the page (or that may be generated by ASP.Net).

For anyone else having the same problem where this code is not preventing the event from firing, this worked for me:
if (window.event.keyCode == 13) {
event.returnValue=false;
event.cancel = true;
}

Related

updatepanel - making other control on page visible or invisible

I'm using a update panel to display some results on a page and it is working fine with no probs.
If though no results were returned I would like a message to display - saying no records found.
The trouble is getting the asp:panel(pnlNoUsers) visible option to be true or false(which contains the no records found message is the prob I'm having
My code for for the update panel is:
<asp:UpdatePanel ID="pnlCust" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlNoUsers" runat="server" visible="false">
<div class="inner-page-title">
<h2>
No records found.</h2>
</div>
</asp:Panel>
<%=show_cust()%>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefresh" />
</Triggers>
</asp:UpdatePanel>
The show_cust() function simply returns a string which will be displayed on the page:
If bHasUsers = False Then
pnlNoUsers.Visible = True
Return ""
End If
pnlNoUsers.Visible = False
Return strUsers & "</ul>"
The panel "pnlNoUsers"visibility property isn;t changing at all?
Anyone know how I can do this?
Thanks,
I don't know the complexity of your requirement but you can skip the conditional logic altogether by using a data control. You can use a gridview control which has an
EmptyDataText property that you can use.
MSDN: Gridview EmptyDataText property
You can manually bind the gridview control with data using DataSource & dataBind properties.
Without your button click event, it is difficult to determine where you might be going wrong. A couple ideas though: Set UpdateMode to Conditional, this is a normal mode to have update panels in, get rid of your inline response write, that is not a good way to handle ASP.NET data display, and add a Literal tag that you can render the user's list. As Damien mentioned, I would use a ListView, Repeater, or GridView (in that order) to render your user list rather than generating an unordered list in code and writing it to the browser.
<asp:UpdatePanel ID="pnlCust" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlNoUsers" runat="server" Visible="false">
<div class="inner-page-title">
<h2>No records found.</h2>
</div>
</asp:Panel>
<asp:Literal ID="CustomerListLiteral" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefresh" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnRefresh" runat="server" OnClick="btnRefresh_Click" />
Handle your update panel efforts in a button click event. My bet is that the response write you had inline was not triggering the update panel to work. This should do what you want.
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs)
Dim bHasUsers As Boolean = False
Dim strUsers As String = String.Empty
If bHasUsers = False Then
pnlNoUsers.Visible = True
Else
pnlNoUsers.Visible = False
CustomerListLiteral.Text = strUsers & "</ul>"
End If
' Force an update refresh if necessary, but this shouldn't be needed
pnlCust.Update()
End Sub
Why you are using the function show_cust(). You can add the functionality in the button click action. because initially the panel is not visible. it need to to be visible while button click ccording to the condition. So add the functioality
`
If bHasUsers = False Then
pnlNoUsers.Visible = True
Return ""
End If
pnlNoUsers.Visible = False
Return strUsers & "</ul>"
on btnRefresh click event. It will work

How to refresh an opened popup extender panel

I have a gridview where I have button for each row. After clicking this button, the Modal PopUp Extender Panel is opened (with PanelName.Show()). The Panel contains a user control, which shows some labels, textboxes,etc. with an additional info binded form SqlDataSource. Until this point it works well. But, when I click another button, the panel is purely shown but the content is not refreshed (based on which button is clicked, some details info should be shown). Basically, the method SqlDataSource_Selecting is called only for the panel popup showing but not anymore.
How can I force panel to be refreshed (reloaded) after each PanelName.Show()??
Thanks in advance.
If I'm understanding your question correctly, I think the problem is that you just need to re-Bind your data bound controls after the user clicks the button to change the Selected item. You can use [ControlName].DataBind() to do that. Does that make sense?
It depends on whether the control(s) you want to refresh are DataBound() or not.
In other words, can you force the control to reload by using a DataBind() method call to force the control to reload itself, with either the same or new data?
Most GUI controls have the DataBind() method, but it's useless if the control is not actually using data to work!
This is why in your case your panel is not "refreshed" with new data because using a DataBind() on the panel does nothing. Using a databind() on the entire GridView is a different story and should work. Maybe place an UPDATEPANEL around the whole lot? If you do you have to be careful your normal edits and other Commands on the rows will continue to work.
However, What you can do is place the modalpopupextender inside your TemplateField, and using a "trick", you can keep your server post backs and still fire the popup panel.
ie
<asp:UpdatePanel ID="upADDMAIN" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnADD" runat="server" Text="NEW LOGIN" BackColor="Blue" Font-Bold="True" ForeColor="#FFFFCC" OnClick="btnADD_Click" />
<asp:Button ID="btnDUM" runat="server" style="display:none" />
<div style="height:20px">
</div>
<ajaxToolkit:ModalPopupExtender ID="mpeADD" runat="server"
targetcontrolid="btnDUM"
popupcontrolid="upADD"
backgroundcssclass="modelbackground">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upAdd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlADD" runat="server" Width="700px" HorizontalAlign="Center" CssClass="auto-style10" Height="200px">
..
..
<div id="puFTR" class="auto-style17" style="vertical-align: middle">
<asp:Button id="btnOK" runat="server" Text="OK" style="width: 80px" OnClick="btnOK_Click" />
<asp:Button id="btnCAN" runat="server" Text="CANCEL" style="width: 80px" OnClick="btnCAN_Click" CausesValidation="False" />
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:UpdatePanel>
As you may see, the btnDUM control is a Dummy to get the MPE to work, but it's not actually used as it's hidden by the style="display:none" tag.
However, the btnADD does work because it calls a Click() method on the server side which does the refresh of data on your new row. You may have to use a little jScript to pass the ROWINDEX into the Click() method for it to work with a GridView.
Incidentally, the Click() method in my case "controls" the MPE manually...
protected void btnADD_Click(object sender, EventArgs e)
{
ClearADDform();
mpeADD.Show();
}
protected void ClearADDform()
{
txtLOGIN.Text = string.Empty;
cbISActive.Checked = true;
txtPWD.Text = string.Empty;
ddlAgent.SelectedIndex = -1;
}
In my case, the above code example is outside a GridView, so you'll need to adjust.
But the point is, you can still have Server Side calls using Ajax popups!
Good luck.

Cancel a cross-page postback?

I have a page that has several ListBoxes that have some cascading filtering based on the selected values using an AutoPostBack. The form takes all the selected values and generates an excel doc by cross-page posting to a different ASPX. The problem is, after clicking submit once, it will continually fire the cross-page postback every time a selection has changed.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListBox ID="ParentItems" runat="server" SelectionMode="Multiple" AutoPostBack="true"></asp:ListBox>
<asp:ListBox ID="ChildItems" runat="server" SelectionMode="Multiple" AutoPostBack="true"></asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Submit" runat="server" PostBackUrl="~/AnotherPageThatGeneratesAnExcelDoc.aspx" />
How do I cancel the cross-page postback from the ListBoxes' SelectedIndexChanged events?
Here's the event in the codebehind:
Protected Sub ParentItems_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ParentItems.SelectedIndexChanged
'' do some filtering of the ChildItems ListBox
'' tried these but they do not work
''Submit.Enabled = False
''Submit.PostBackUrl = String.Empty
'' I also tried wrapping the button in a PlaceHolder and hiding/removing it, neither worked
''Buttons.Visible = False
''Buttons.Controls.Remove(Submit)
End Sub
This is my current solution using javascript. It works, but seems like a hack:
// using jQuery, add a click event that resets the form action
$("select[multiple]").click(function () {
this.form.action = this.form._initialAction;
});
Edit: adding a click event in the codebehind:
ParentItems.Attributes("onclick") = "this.form.action = this.form._initialAction;"
The problem is that using the PostbackUrl property resets the form action to a new URL, and your Ajax calls (or any subsequent postbacks) use whatever the current action of the form is.
Your solution doesn't work because the submit button isn't part of your UpdatePanel, so it never gets modified.
The easiest solution might be to move your Excel file generating code out of the page it's in, and into the page you're looking at, in the click handler of the button.
You also could probably include an iframe on the page you're looking at, and on submit, rather than going to a new page, set the source of the iframe to the Excel-generating page.
Both of these would avoid the need for using the PostbackUrl.

jQuery click disappears into some abyss

Here is my setup:
I have an asp.net button on a page --
<asp:Button id="btnSelectEmp" runat="server" Text="Select Employee" />
I have a .js file with the following jQuery click event --
$("input[id$='_btnSelectEmp']").click(function ($e) {
$("div[id$='_divEmpSearch']").css("display", "inline");
$e.preventDefault();
});
As you can see, clicking upon the button will set a div visible. Nothing special; not rocket science.
The div is wrapped with an asp.net update panel, and it contains an asp.net user control (.ascx)
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="divEmpSearch" runat="server" style="display: none;">
<uc:EmpSearch ID="ucEmpSearch" runat="server" />
</div>
// And a bunch of other controls that are updated according to whatever the user selects in the user control above
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ucEmpSearch" />
</Triggers>
</asp:UpdatePanel>
The user control above is also wrapped in an asp.net update panel, because it has to communicate with the server. Among other controls like textboxes and such, the user control has two buttons upon it: 1) an asp.net button that does a postback and 2) an asp.net button that does an asynchronous postback.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /
<br />
asp:Button ID="btnContinue" runat="server" Text="Select" OnClick="btnContinue_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
<asp:PostBackTrigger ControlID="btnContinue" />
</Triggers>
</asp:UpdatePanel>
The button in the user control that does a postback is working great. I click it, a postback occurs and my div control is re-hidden. I can then click on the Select Employee button (the one that I supplied the code for at the very first of the question) and the jQuery click event is handled and the div will be reshown.
However, the button in the user control that does an asynchronous postback works also, but after it hides the div, if I then click on the Select Employee button the jQuery click event will not be handled.
What this tells me is that for some reason during an asynchronous postback to the page, something happens to the Select Employee button so that the jQuery click event no longer happens. Why?
Your button is replaced with a new one when your update panel comes back with new content, so this:
$("input[id$='_btnSelectEmp']").click(function ($e) {
Binds to the elements it finds at that time, instead you'll want .delegate() or .live() here to listen for click events from current and future elements, like this:
$("input[id$='_btnSelectEmp']").live("click", function ($e) {
$("div[id$='_divEmpSearch']").css("display", "inline");
$e.preventDefault();
});
Or a bit cheaper using .delegate():
$("#container").delegate("input[id$='_btnSelectEmp']", "click", function ($e) {
$("div[id$='_divEmpSearch']").css("display", "inline");
$e.preventDefault();
});
In this case #container should be a parent of the update panel, one that doesn't get replaced in the postback.
Use the live() function. live() delegates the click event to a parent element, so the element (in this case btnSelectEmp) doesn't need to exist at the time the event is bound.
$("#<%=btnSelectEmp.ClientID%>").live("click" function ($e) {
$("#<%=divEmpSearch.ClientID%>").css("display", "inline");
$e.preventDefault();
});
What is happening is the btnSelectEmp button is getting replaced by the asynchronous call and the new element has not been bound to an event handler.
Also, I've modified the jquery selector here to use the exact client id of the element. This will improve speed, plus I seem to recall certain selectors don't work with event delegation in certain versions of Jquery.
try live('click', function(){...}) instead of click(function(){...})
Wild guess : "_btnSelectEmp" is used more than once?

FileUpload in FormView inside an UpdatePanel

The Scenario:
I have an ASP.Net webpage which I intend to use for letting the user(not the real users, but content manager basically) insert and edit the records in a table using a FormView. This FormView is inside an UpdatePanel, as I'm also using cascading dropdownlists to let the user select some values.
Now, this FormView also contains 4 FileUpload controls, and as you might know that these fileupload controls require a full postback since most browsers do not let Javascript access the disk. So, this problem would have been solved by doing something like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="InsertButton" />
<asp:PostBackTrigger ControlID="UpdateButton" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
Edit: Forgot to add that the fileuploading takes place in the OnUpdating and OnInserting events of the SqlDataSource.
The Problem:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup. And MSDN says that:
Programmatically adding
PostBackTrigger controls is not
supported.
Please suggest some solution to make this work. Any insight on the matter is highly appreciated. Thanks.
P.S.- A workable solution for me was to set the UpdatePanel's PostBackTrigger as the whole FormView itself:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
But now due to a bit of change in requirements, this solution(if you call it a solution) is not acceptable.
Have you given a though about using Iframe for doing the postback ? something like:
<iframe name="uploader" id=uploader
src="uploaderSender.aspx?AllowedExtension=<%= AllowedExtension %>&StoringPath=<%= StoringPath %>&StoringFileName=<%= StoringFileName %>&OldFileName=<%= OldFileName %>&MaximumSize=<%= MaximumSize %>"
width="450" height="50" frameborder=0 scrolling=no >
</iframe>
with uploaderSender.aspx like :
<form action="UploaderReceiver.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" onchange="document.getElementById('IsFileUploading').style.visibility = 'visible'; document.forms[0].submit()"/>
<span id="IsFileUploading" style="visibility: hidden">
<asp:Image ID="Image1" runat="server" ImageUrl="~/immagini/Ajax-loader.gif" />
</span>
</form>
and UploaderReceiver.aspx like :
protected void Page_Load(object sender, EventArgs e)
{
//if there is one file to process
if (Request.Files.Count > 0)
//create the folder if it does'nt exists and returns the local path to get it
string StoringPathToBeSaved = StoringPath.GetFolderPath();
// append the name of the file to upload to the path.
StoringPathToBeSaved = StoringPathToBeSaved + StoringFileName + Extension;
Request.Files[0].SaveAs(StoringPathToBeSaved);
}
this is just bits of code just for you to figure out if you would be interested in this way of dealing with the upload, I can give you more if you want after.
see you, and good luck with your code,
Yay!! Finally got it to work!
Here's How:
Well contrary to what MSDN says, we can in fact add PostBack Triggers Programmatically. Not necessarily to the UpdatePanel, but to the ScriptManager.
After hours of playing around, here's what worked:
We are not able to access controls inside a FormView, untill the template has been rendered, so we can only add postback triggers after the formview's OnDataBound Event.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
LinkButton lb = (LinkButton)FormView1.FindControl("UpdateButton");
ScriptManager.GetCurrent(Page).RegisterPostBackControl(lb);
}
//Similarily you can put register the Insert LinkButton as well.
}
And now, if your UpdatePanel causes ConditionalUpdate, you can do something like this to make it work:
The Markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>..
<EditItemTemplate>
...
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClick="Cause_PostBack"CommandName="Update">Update</asp:LinkButton>
...
</EditItemTemplate>
..</ContentTemplate>
</asp:UpdatePanel>
CodeBehind:
//call this function as the OnClick Event Handler for the Controls you want to register as
//triggers.
protected void Cause_PostBack()
{
UpdatePanel1.Update();
}
Otherwise, if your situation allows it(as mine does), just set the UpdatePanel's UpdateMode="Always"
This is old, but was trying to solve another problem and ran into this. This wasn't my problem, but here's an alternative for anyone new who runs into this as well.
You stated your problem as:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup
You actually can access their ID's through markup to use as the ControlID in the PostBackTrigger. You just have to use the button's name that is created in the page html mark-up as the ControlID. You can find the name created by viewing the page source when you're viewing the page in the browser. It typically is the name of the FormView + $ + name of the button.
For example, let's say you have a FormView named "FormView1" that contains an Insert button which you gave the ID of "btnInsert" during design. If you open up your page in the browser to view it live and then view the page's source, you'll notice that the html mark-up of the button will actually be given the name "FormView1$btnInsert".
Use that name as the ControlID in your PostBackTrigger and your update panel will work.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1$btnInsert" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>

Resources