Showing posts with label user. Show all posts
Showing posts with label user. Show all posts

Wednesday, March 28, 2012

Difficult to disable ClientState in User Control

Not sure there's a solution for this, but I find it overly difficult to disable the client state field. I'm using HTTP Get for my post, and I have a textbox watermark extender on a field. I don't want the ClientState because it makes my URLs look bad. So I have to set EnableClientState to false BEFORE the client state hidden control is actually set. In a user control, I don't think I get any chance to do this. (The debugger says I don't see OnInit before the contained TextBoxExtender does, and there's no PreInit for the control).

So my only choice would be to derive from TextBoxWatermarkExtender. Not the end of the world, but I don't think it's what was intended. Thoughts?

Your idea about deriving from TBW seems pretty reasonable to me. Any objections?
Yeah, it's an awfully heavy price to pay for simply setting a property. I would much prefer to see this in the core classes.

Monday, March 26, 2012

Detailsview ItemUpdate Event with UpdatePanel

I have a grid with individuals in it, the user selects and individual which populates a Detailsview below. Both gridview and Detailsview are wrapped with UpdatePanels. The user can then edit the individual in the Detailsview and submit changes when updateing. Now the updatepanel wrapping the gridview has an <asp:AsyncPostBackTrigger tied back to the Detailsview's ItemUpdated event.

I ultimately want the grid of selected individuals to update whenever the user makes changes to the individuals through the supporting gridview, the trigger I am using is not providing the functionality I am looking for, what approach should I take next? or is this trigger not working properly?

I can provide code-snippets, but figured it would be better to get a high level overview then look at some of my mess :)

Thanks in advance to anyone who offers help.

Here are some sample codes for your reference.
.ASPX
<div>
<asp:UpdatePanel ID="gvUpnl" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvProduct" runat="server" AutoGenerateSelectButton="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" DataKeyNames="ProductID" DataSourceID="sqlDS" OnRowCommand="gvProduct_RowCommand">
<Columns>
<asp:TemplateField HeaderText="ProductID" SortExpression="ProductID">
<ItemTemplate>
<asp:Label ID="lblProductID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity" SortExpression="Quantity" />
<asp:BoundField DataField="TransactionDate" HeaderText="TransactionDate" ReadOnly="True"
SortExpression="TransactionDate" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS" runat="server" ConnectionString="<%$ ConnectionStrings:ProductConnectionString %>" DeleteCommand="DELETE FROM [Product] WHERE [ProductID] = @.ProductID" InsertCommand="INSERT INTO [Product] ([ProductName], [UnitPrice], [Quantity], [TransactionDate]) VALUES (@.ProductName, @.UnitPrice, @.Quantity, @.TransactionDate)" SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [Quantity], [TransactionDate] FROM [Product]" UpdateCommand="UPDATE [Product] SET [ProductName] = @.ProductName, [UnitPrice] = @.UnitPrice, [Quantity] = @.Quantity, [TransactionDate] = @.TransactionDate WHERE [ProductID] = @.ProductID">
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Double" />
<asp:Parameter Name="Quantity" Type="Int32" />
<asp:Parameter Name="TransactionDate" Type="DateTime" />
<asp:Parameter Name="ProductID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Double" />
<asp:Parameter Name="Quantity" Type="Int32" />
<asp:Parameter Name="TransactionDate" Type="DateTime" />
</InsertParameters>
</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvProduct" EventName="RowCommand" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="dvUpnl" runat="server">
<ContentTemplate>
<asp:DetailsView ID="dvProduct" runat="server" DataKeyNames="ProductID" AllowPaging="True" DataSourceID="dvDS" AutoGenerateEditButton="true" AutoGenerateInsertButton="true" AutoGenerateDeleteButton="true">
</asp:DetailsView>
<asp:SqlDataSource ID="dvDS" runat="server" ConnectionString="<%$ ConnectionStrings:ProductConnectionString %>">
<SelectParameters>
<asp:Parameter Name="ProductID" Type="Int32" Direction="Input" DefaultValue="1"/>
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ProductID" Type="Int32" Direction="Input" />
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="double" />
<asp:Parameter Name="Quantity" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</div
Behind Code:
protected void Page_Load(object sender, EventArgs e)
{
string cString = System.Configuration.ConfigurationManager.AppSettings["ProductConnectionString"];
dvDS.ConnectionString = cString;
dvDS.SelectCommand = "SELECT ProductID,ProductName,UnitPrice,Quantity,TransactionDate FROM Product WHERE ProductID=@.ProductID";
dvDS.UpdateCommand = "UPDATE Product SET ProductName=@.ProductName,UnitPrice=@.UnitPrice,Quantity=@.Quantity WHERE ProductID=@.ProductID";
}

protected void gvProduct_RowCommand(object sender, GridViewCommandEventArgs e)
{
Label lblProductID = gvProduct.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lblProductID") as Label;
string productID = lblProductID.Text;
if(e.CommandName == "Select")
{
dvDS.SelectParameters["ProductID"].DefaultValue = productID;
}
else if(e.CommandName == "Edit")
{}
else if(e.CommandName == "Delete")
{}
}
Wish the above can help you.

DetailsView & ObjectDataSource: Cancel Insert but Retain User Input

Hi,

I need to cancel an insert operation during a DetailsView/ObjectDataSource insert event, and display to the user the same insert page with their previously entered values. For example, after a server side input validation the user may need to modify some of the values they entered.

Canceling insert is easy in the ObjectDataSource.Inserting event handler: e.Cancel = true;

However, this cancels insert mode and the values the user input are lost. The ObjectDataSource.Inserting event handler has access to the input parameters, which contain the values the user has entered. It is possible to put the DetailsView object back into insert mode: DetailsView1.DefaultMode = DetailsViewMode.Insert; but I don't know how to programatically assign the user values to the fields, since I do not know how to get a handle to the field.

How does one retain the user input values in insert mode when canceling an inserting event in the DetailsView/ObjectDataSource programming model?

Thanks,

Paul

You should validate the input values in the DetailsView ItemInserting event, rather than in the ObjectDataSource Inserting event. In such case the input values will be retained though you cancel the inserting event

protected void DetailsView1_ItemInserting (object sender, DetailsViewInsertEventArgs e)
{
// validate
e.Cancel = true;
}

Thanks

-Mark post(s) as "Answer" that helped you

Design question - UpdatePanel wrapping a GridView

As a general UI design question, I was wondering if it even makes sense (gives any improvement in the user experience, that is) to wrap a GridView in an UpdatePanel, considering that the page's sole purpose is to search for X and the grid displays the search results. There is not much that the user can do with in the page, basically search, view the results, sort them and go to next/previous page of search results.

Is it really worth it? What would be the pros/cons?

Well, I tend to avoid update panels in any case, but assuming you prefer that as your ajax delivery mechanism, I'd say that it still makes sense. Very few pages are completely devoid of anything but a data view; most have (at least) navigation to other pages and some form of branding. Most pages have quite a bit more in terms of markup, including images and other style elements. In short, yeah, there's still some payoff. I'd argue, actually, that a page with just one server-side control is actually a better cantidate for an updatepanel, b/c more server controls = bigger viewstate = less value from your update panel b/c of weight on the wire.


i'm all for wrapping the gridview in an updatepanel. I'm currently writing an app that is 100% postback-less and wrapped in update panels, and with my gridviews i am able to filter, sort, and page the results without a flicker. also, if done correctly, the amount of data transferred over the wire will be less than with a full postback, however, you will not save any memory space on the server, you may even use a little more but not a big deal.


Try the Asp.net Ajax Grid.http://dotnetslackers.com/articles/ajax/ASPNETAjaxGridAndPager.aspx

Saturday, March 24, 2012

Deployment Problem

I'm a very new user of Atlas. I have a .NET application where I wanted to do some AJAX and Atlas seemed like a great choice. It was pretty simple to create a web service and get it accessible to my application through Atlas on my development PC.

But now that I'm trying to get it on the production server, I'm running into some problems that I can't overcome - after about 8 hours of trying. I've read through the forums and Googled before this post - but hopefully I'm just missing something silly that someone can help me with. I'm at my wits end!

The application is unable to access the web service (update.asmx) with the /js tag appended. If I run Fiddler, I see the application does attempt to connect to update.asmx/js. But I get a 500 error. If I connect the update.asmx, I get the expected Service Description and it seems to be working. If I connect to update.asmx/js, I get a "Server Error in '/' Application" page back. Doing this on my development box, I see the appropriate JavaScript that Atlas provides to register the service.

I haven't been able to determine the cause. ASP.NET 2.0 is installed on the server - the TreeView control works within my application and the error page when I try to access update.asmx/js indicates ASP.NET Version:2.0.50727.42. This is a Windows 2003 SP1 Server w/ IIS 6. I verified that I completed all tasks from the installation document on integrating Atlas into an existing application. I'm appending my Web.Config file to the end of this post.

Please let me know what direction to go next to troubleshoot the problem. I've been banging my head on this one for a long time. Thanks a lot in advance!

Here is my Web.Config file:

<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<sectionGroup name="microsoft.web" type="Microsoft.Web.Configuration.MicrosoftWebSectionGroup">
<section name="converters" type="Microsoft.Web.Configuration.ConvertersSection"/>
</sectionGroup>
</configSections>
<microsoft.web>
<converters>
<add type="Microsoft.Web.Script.Serialization.Converters.DataSetConverter"/>
<add type="Microsoft.Web.Script.Serialization.Converters.DataRowConverter"/>
<add type="Microsoft.Web.Script.Serialization.Converters.DataTableConverter"/>
</converters>
</microsoft.web>
<appSettings/>
<connectionStrings>
<add name="NetworkConnectionString" connectionString="Data Source=server1;Initial Catalog=Network;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="RADConnectionString" connectionString="Data Source=server2;Initial Catalog=db;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="STConnectionString" connectionString="Data Source=server1;Initial Catalog=ST;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<pages>
<controls>
<add namespace="Microsoft.Web.UI" assembly="Microsoft.Web.Atlas" tagPrefix="atlas"/>
<add namespace="Microsoft.Web.UI.Controls" assembly="Microsoft.Web.Atlas" tagPrefix="atlas"/>
</controls>
</pages>

<!-- ASMX is mapped to a new handler so that proxy javascripts can also be served. -->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="Microsoft.Web.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="Microsoft.Web.Services.ScriptModule"/>
</httpModules>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" defaultLanguage="c#" urlLinePragmas="true">
<assemblies>
<add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
-->
</system.web>
</configuration>

I forgot to mention that I also uninstalled and reinstalled the .NET framework in troubleshooting the problem and created a new web site with \inetpub\wwwroot. Neither of these helped.

And to answer my own question, I was missing a few lines in the Web.Config file.

In the <configSections> section I needed:

<

sectionname="webServices"type="Microsoft.Web.Configuration.WebServicesSection"requirePermission="false" />

And in the <microsoft.web> section I needed:

<

webServicesenableBrowserAccess="true" />

This got me working correctly.

Deny a collapsible Panel Extender from collapsing if required field validators arent valid

Hi all,

I am using an collapsible Panel Extender that has a panel with textboxes used for sending a message.

When a user needs to send a message he expands the panel then fills in the boxes and presses the send button that

will send the message and collapse the panel as well.

I want to prevent the panel from collapsing if the required field validators are not valid.

I am not that great in javascript so please try and elaborate as much as possible.

Thanks.

Hi Itay,

Itay molecule:

I am not that great in javascript so please try and elaborate as much as possible.

Is is this javascript that collapses the panel?

Here is some javascript code that checks on the clientside if the page is valid. Merge this code with your javascript ;)

 <script type="text/javascript"> function checkValidity() { if (Page_ClientValidate() == false) {//handle the fact that some controls are not valid! } } </script>

If you have questions/remarks please do so!
Kind regards,
Wim


Would it be a solution to use a little updatepanel for an async postback allowing you (the server) to either:

- disable or hide the ExpandControlID ?

- (temporarily) change the target control id of the CollapsiblePanelExtender to a hidden button (style="display:none;") ?


Actually this is not an option because my collapse button is the "send" button that is supposed to check the validation

of the form.


Hi Itay,

Itay molecule:

Actually this is not an option because my collapse button is the "send" button that is supposed to check the validation

of the form.

My solution will do!
If you allow javascript in the browser offcourse.

Give me your panelcode and I'll show you what to adapt!

Kind regards,
wim


Wim Hi,

My reply wasn't ment for you i am sure your solution is the way to do it.

Here is my code thanks alot for the help.

c#

protectedvoid ImageButton1_Click(object sender,ImageClickEventArgs e)

{

sendmail sendusamail =newsendmail();

sendusamail.sendmail1(Subject.Text + "from: " + From.Text );

}

ASPX

<body>

<formid="form1"runat="server">

<div>

<asp:ScriptManagerID="ScriptManager1"runat="server">

</asp:ScriptManager>

<asp:ImageButtonID="ImageButton1"runat="server"ImageUrl="~/animalsbusinessid/c2a1_66.png"OnClick="ImageButton1_Click1"CausesValidation="False"/>

<asp:PanelID="Panel1"runat="server"Height="7px"Width="376px"Direction="RightToLeft"HorizontalAlign="Center">

<asp:LabelID="Label1"runat="server"Font-Bold="True"></asp:Label>

<asp:TextBoxID="From"runat="server"Columns="23"></asp:TextBox><br/>

<asp:TextBoxID="UsersEmail"runat="server"Columns="23"></asp:TextBox>

<asp:TextBoxID="Subject"runat="server"Columns="23"></asp:TextBox>

<asp:TextBoxID="Body"runat="server"Columns="30"Rows="8"TextMode="MultiLine"></asp:TextBox>

<br/>

<asp:RequiredFieldValidatorID="RequiredFieldValidator2"runat="server"ControlToValidate="UsersEmail"

Display="Dynamic"ErrorMessage="please fill in your address"Font-Bold="False"Font-Size="13px"></asp:RequiredFieldValidator>

<asp:RequiredFieldValidatorID="RequiredFieldValidator1"runat="server"ControlToValidate="From"

Display="Dynamic"ErrorMessage="please fill in your name"Font-Bold="False"Font-Size="13px"></asp:RequiredFieldValidator>

<asp:RequiredFieldValidatorID="RequiredFieldValidator3"runat="server"ControlToValidate="Body"

Display="Dynamic"ErrorMessage="write your message"Font-Bold="False"Font-Size="13px"></asp:RequiredFieldValidator><br/>

<asp:ImageButtonID="ImageButton2"runat="server"ImageUrl="~/animalsbusinessid/mailto_10.png"OnClick="ImageButton1_Click"/>

<asp:RegularExpressionValidatorID="RegularExpressionValidator1"runat="server"ControlToValidate="UsersEmail"

Display="Dynamic"ErrorMessage="this is not a valid email address"Font-Bold="False"Font-Size="13px"ValidationExpression="\w+([-+.']\w+)*@.\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></asp:Panel>

</div>

<ajaxToolkit:CollapsiblePanelExtenderID="cpe"runat="server"

TargetControlID="Panel1"

CollapsedSize="30"

ExpandedSize="500"

Collapsed="True"

ExpandControlID="ImageButton1"

CollapseControlID="ImageButton2"

AutoCollapse="False"

AutoExpand="False"

ScrollContents="False"

TextLabelID="Label1"

CollapsedText="Show Details..."

ExpandedText="Hide Details"

ExpandDirection="Vertical">

</ajaxToolkit:CollapsiblePanelExtender>

</form>

</body>


Hi Itay,

The following code should do the trick.

More info about the $find function here:http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/ApplicationClass/SysApplicationFindComponentMethod.aspx

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function handleCollapse(extenderId)
{
//Find your CollapsiblePanel Behavior on the page.
var myBehavior = $find(extenderId)

//if the page is not valid, do something
if(!Page_ClientValidate())
{
//what I do here is dispose the behavior. This way the collapse will be cancelled.
myBehavior.dispose();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="my image.jpg" OnClick="ImageButton1_Click1" CausesValidation="False" />
<asp:Panel ID="Panel1" runat="server" Height="7px" Width="376px" Direction="RightToLeft" HorizontalAlign="Center">
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:TextBox ID="From" runat="server" Columns="23"></asp:TextBox><br />
<asp:TextBox ID="UsersEmail" runat="server" Columns="23"></asp:TextBox>
<asp:TextBox ID="Subject" runat="server" Columns="23"></asp:TextBox>
<asp:TextBox ID="Body" runat="server" Columns="30" Rows="8" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="UsersEmail"Display="Dynamic" ErrorMessage="please fill in your address" Font-Bold="False" Font-Size="13px"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="From"Display="Dynamic" ErrorMessage="please fill in your name" Font-Bold="False" Font-Size="13px"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="Body"Display="Dynamic" ErrorMessage="write your message" Font-Bold="False" Font-Size="13px"></asp:RequiredFieldValidator><br />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="confirm_icon.gif" OnClick="ImageButton1_Click"OnClientClick="handleCollapse('cpe')"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="UsersEmail"Display="Dynamic" ErrorMessage="this is not a valid email address" Font-Bold="False" Font-Size="13px" ValidationExpression="\w+([-+.']\w+)*@.\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></asp:Panel>
</div>
<ajaxToolkit:CollapsiblePanelExtender ID="cpe" runat="server"TargetControlID="Panel1"CollapsedSize="30"ExpandedSize="500"Collapsed="True"ExpandControlID="ImageButton1"CollapseControlID="ImageButton2"AutoCollapse="False"AutoExpand="False"ScrollContents="False"TextLabelID="Label1"CollapsedText="Show Details..."ExpandedText="Hide Details"ExpandDirection="Vertical" >
</ajaxToolkit:CollapsiblePanelExtender>
</form>
</body>
</html>

If you have questions/remarks please do so!

Kind regards,
Wim


Thanks alot Wim,

Everything is almost up and running.

Just one little thing.

My collapse button doesn't collapse the panel on the first click even if the validation are valid.

Only the second time i click the button the panel collapeses back.

Any thoughts?


Hi Itay,

Hmm, that behavior is not right :)

Did you also have that behavior when you use my code example AS IS? Or is it only specific to your code?
If it is only occuring in your code, then please give me the code that replicates this behavior.

If it is also in my example, then I must say that it was not happening to me!
Can you please give me your browser version where you are noticing this behavior?
Also try your code in another browser and see if it also happens over there.

Please comment on my observations.
Kind regards,
Wim


Hi,

I tried using your code and the same thing happened. I will be more specific.

After expanding the panel i press the collapse panel in order to check that it won't collapse if not valid.

Then i fill in the required filled and press the collapse button again this time no none of the required fields error messages pop up

but the panel doesn't collapse as well then i press the collapse button again and it collapses the panel from there on

expanding or collapsing the panel works with a single click.

I did have a problem that every collapse or expanding the page would flicker (postback)

solved it with adding the

suppresspostback="true"

to theCollapsiblePanelExtender.

I am using IE7 version 7.0.5730.11

and again thanks for the help.


Wim do you have any idea to how i can resolve this problem?


Itay molecule:

Wim do you have any idea to how i can resolve this problem?

Sorry Itay that I didn't get back to you any sooner ....

I looked at the example again (the one I created):

it is not good!

Hi Wim

Every thing works great just one little thing

in order to send the message on the panel

i need the collapse button/img ti initialize a postback calling the sendmail function

is there a way that the javascript function will create the postback as well?


Hi itay,

Ok I forgot about that functionality you needed.

I didn't try it yet, but I think you could use an ImageButton for that second one. The IMG that triggers the javascript. Then just set the javascript function in the OnClientClick of it. ImageButtons have those right? Then I think it's possible to NOT let the button postback until the page is valid. Look at the button's properties. Is it the CausesValidation property, I'm not sure ...

I would go for a setup like that!

Please give it a try and if it doesn't work out I'll look into it.

Kind regards,
Wim


Wim thanks

it works just fine

still getting a page refresh on the onclick="... from the image button

but that's expected

i will try to rap it up in an update panel.

Thanks a lot

hope some day i will the ability to help you back.

Wednesday, March 21, 2012

Default Button Issue

Hi Everyone

I have a asp Panel with few textboxes and two ImageButtons - imgbtnSave and imgbtnCancel

Now what i want that whenever the user presses enter button as long as he is inside that asp Panel, the default button (say I want "imgbtnSave" as Default Button) works.

Note : - I am using my own JavaScript code for DateValidation. So if i use inbuilt defaultButton property of asp Panel then DateValidation fails. I cant change the DateValidation function now as my project is on deliverey stage. So i want JavaScript Code for Default Button

Thanx in advance

you want to set focus to ImageSave button

you can do like this

write the function in javascript

<script type="text/javascript" language="javascript">
function setFocus()
{
document.getElementById("<%= Button.ClientID %>").focus();


}
</script>

call this function like this

protected void ButtonAddCategory_Click(object sender, EventArgs e)
{

ClientScript.RegisterStartupScript(typeof(Classname), "Focus", "setFocus();", true);

}

give me the feedback

-----------

mark as Answer if you feel


Hi Manoj

Thanx for your valuable time....

The solution you have given works in the condition where we have one textbox associated with a single Button.

Now suppose i have Panel inside which i have 60 textBoxes and One Imagebutton

And Other Panel inside which i have 20 textboxes and 2 ImageButton.

Now what should i do???
Hope u understand now

Bye and Take Care

Thanx in advance


Hi DeepakTake a look at the following code:

1 private void SetDefaultButton(TextBox control, Button btButton)
2 {
3 control.Attributes.Add("onkeydown",
4 "if(event.which || event.keyCode)"
5 +"{"
6 + "if ((event.which == 13) || (event.keyCode == 13)) "
7 + "{"
8 + "document.getElementById('" + btButton.UniqueID +"').click();"
9 + "return false;"
10 + "}"
11 +"}"
12 +"else"
13 +"{"
14 + "return true;"
15 +"};" );
16 }
17
18 private void SetDefaultButton(TextBox control, ImageButton btButton)
19 {
20 control.Attributes.Add("onkeydown",
21 "if(event.which || event.keyCode)"
22 +"{"
23 +"if ((event.which == 13) || (event.keyCode == 13)) "
24 +"{"
25 +"document.getElementById('" + btButton.UniqueID +"').click();"
26 +"return false;"
27 +"}"
28 +"}"
29 +"else"
30 +"{"
31 +"return true;"
32 +"};");
33 }
34
35 protected void Page_Load(object sender, EventArgs e)
36 {
37 SetDefaultButton(this.TextBox1,this.Button1);
38 SetDefaultButton(this.TextBox2,this.Button2);
39 SetDefaultButton(this.TextBox3,this.ImageButton1);
40 }
41
42 protected void Button1_Click(object sender, EventArgs e)
43 {
44 this.Label1.Text ="Button 1 was clicked";
45 }
46
47 protected void Button2_Click(object sender, EventArgs e)
48 {
49 this.Label1.Text ="Button 2 was clicked";
50 }
51
52 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
53 {
54 this.Label1.Text ="Image button was clicked";
55 }
56

And on the .ASPX page, I have the following the following controls:

1 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
2 <br />
3 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
4 <asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" /><br />
5 <br />
6 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
7 <asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button2_Click" /><br />
8 <br />
9 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
10 <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/Save.png" OnClick="ImageButton1_Click" />

I have placed three textboxes, and each has an associated button.  The third textbox has an imagebutton
next to it. Enter something in the textbox, and press the enter key. It executes the associated click event
for each of them.
The trick over here is to add a small piece of JavaScript code.  I have formatted the code so that you can
understand what it actually does. The trick here is that since I need to make sure it works for IE and Firefox,
I have identify the ENTER KEY (key code 13), using both event.keyCode and event.which (for FireFox), to
fire its respective click.
And to make this implementation easily replicatable, I have turned this JavaScript add-on as a generic function,
which is called from the Page_Load method (as shown in this example). It is overloaded to handle both ordinary
buttons, and imagebuttons.
Hope this helps.
In case you find this suitable, please don't forget to mark it as the answer.
Happy coding!
MANOJ KUMAR SHARMA
www.manojkumarsharma.com