Showing posts with label control. Show all posts
Showing posts with label control. Show all posts

Thursday, March 29, 2012

Please advise about caching

Hello,

I tried out using the cache the other day and was impressed with the
concept. I built myself a custom control to generate the site links,
using an XML file for the info. I kept the XML file in the cache and
added a dependency so it will notice when the file changes. All fine so
far.

I was reading last night about using the OutputCache page directive to
store the page in the cache. It seems you can do this for a user control
as well, allowing you to cache part of a page.

So, my question is, which is more appropriate, using the cache manually
or using the OutputCache page directive? Obviously each will have its
uses, but consider the following ...

I have an e-commerce site written in Classic ASP. I am looking to
rewrite it in ASP.NET at some point. One weakness of the existing
version is that product pages are generated dynamically from a database.
I had been looking at a method whereby when the database is updated, the
HTML is created for the product and written to disk, avoiding the
necessity to hit the database each time the page is displayed.

I am now wondering if it would be better to generate the HTML and store
it in the cache. I could either write the part of the page that displays
that product details as a custom control and use OutputCache to cache
that control, or generate the HTML myself and add it manually to the
cache. Either way I would need some mechanism for checking when the
database is updated, but that's a separate issue.

So, any suggestions? Anything to sway me one way or the other?

One factor I would like to consider is the life of an object in the
cache. The OutputCache directive takes a Duration parameter, which means
that come what May, the HTML will be dropped from the cache when it
expires 9if not sooner). If I put it in the cache manually, AFAIK it
will stay there until it gets kicked out for lack of space. Presumably
an object that is called often is less likely to get kicked out, so the
HTML for the most popular products will stay in the cache the longest,
ensuring maximum efficiency. Is this right?

TIA for any comments on this long waffly post ;-)

--
Alan Silver
(anything added below this line is nothing to do with me)Alan:
Generally I like to use OutputCache whenever possible, and storing things in
the HttpCache after. OutputCache caches the entire rendered HTML,
HttpCache.Insert/Add only chunks of data (in other words you still need to
render the output).
In IIS 6.0, outputcache is automatically hosted in the kernel which makes it
even faster. In 2.0 outputcache will be even more flexible AND allow you to
store it to the file which will let it last forever (if you wanted to).

As far as performance, the closer to the final product you can cache
(outputcache) the better. And while I typically don't harp on performance,
that's the point of caching so...

Karl
--
MY ASP.Net tutorials
http://www.openmymind.net/

"Alan Silver" <alan-silver@.nospam.thanx> wrote in message
news:JLmJ3uERv3CCFwyT@.nospamthankyou.spam...
> Hello,
> I tried out using the cache the other day and was impressed with the
> concept. I built myself a custom control to generate the site links,
> using an XML file for the info. I kept the XML file in the cache and
> added a dependency so it will notice when the file changes. All fine so
> far.
> I was reading last night about using the OutputCache page directive to
> store the page in the cache. It seems you can do this for a user control
> as well, allowing you to cache part of a page.
> So, my question is, which is more appropriate, using the cache manually
> or using the OutputCache page directive? Obviously each will have its
> uses, but consider the following ...
> I have an e-commerce site written in Classic ASP. I am looking to
> rewrite it in ASP.NET at some point. One weakness of the existing
> version is that product pages are generated dynamically from a database.
> I had been looking at a method whereby when the database is updated, the
> HTML is created for the product and written to disk, avoiding the
> necessity to hit the database each time the page is displayed.
> I am now wondering if it would be better to generate the HTML and store
> it in the cache. I could either write the part of the page that displays
> that product details as a custom control and use OutputCache to cache
> that control, or generate the HTML myself and add it manually to the
> cache. Either way I would need some mechanism for checking when the
> database is updated, but that's a separate issue.
> So, any suggestions? Anything to sway me one way or the other?
> One factor I would like to consider is the life of an object in the
> cache. The OutputCache directive takes a Duration parameter, which means
> that come what May, the HTML will be dropped from the cache when it
> expires 9if not sooner). If I put it in the cache manually, AFAIK it
> will stay there until it gets kicked out for lack of space. Presumably
> an object that is called often is less likely to get kicked out, so the
> HTML for the most popular products will stay in the cache the longest,
> ensuring maximum efficiency. Is this right?
> TIA for any comments on this long waffly post ;-)
> --
> Alan Silver
> (anything added below this line is nothing to do with me)
>Alan:
>Generally I like to use OutputCache whenever possible, and storing things in
>the HttpCache after. OutputCache caches the entire rendered HTML,
>HttpCache.Insert/Add only chunks of data (in other words you still need to
>render the output).

OK, that's not such a huge problem, it's only a case of pulling it from
the cache and writing it out.

I was more thinking about the issue of how long objects live in the
cache. If I put them in myself, won't they stay there until the cache
gets full? Also, I'm assuming that when objects get dropped form the
cache, the least recently used ones will go first. If so, then the HTML
for the most frequently accessed pages will stay in the cache the
longest, giving the best performance increase.

If I understand the OutputCache right, objects will only stay in the
cache for the time specified. That way, even the frequently accessed
bits will be dropped. This sounds less efficient.

Or have I got it completely wrong ;-)

Thanks for the reply. Any further info would be greatly appreciated.

--
Alan Silver
(anything added below this line is nothing to do with me)
Alan:
I wouldn't say one will last in the cache longer than the other. HttpCache
can also have a time to stay in cache (either as an absolute or a "from last
access"). So in that sense you have more control. I wouldn't make any
assumptions about how/when items are dumped from the cache for two reasons.
First it's probably complicated. Second you shoulnd't assume it's in the
cache technically (ie, it isn't guaranteed to be there, so you need to write
the code to get it form the store if it isn't). Having said that, you can
specify the Priority with HttpCache, again giving you more control, but
adding to the complexity of what/when will be dropped. I would expect a
number of factors to play into the decision, such as priority, time last
used, size, frequency of use, available memory, ....

if you are worried about the duration of output cache, put it as 86400 (a
day)... There's no doubt though that HttpCache provides more flexibility
(priority, absolute vs relative time, dependencies (big one)).

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/

"Alan Silver" <alan-silver@.nospam.thanx> wrote in message
news:MFwoUbGJH5CCFwSE@.nospamthankyou.spam...
> >Alan:
> >Generally I like to use OutputCache whenever possible, and storing things
in
> >the HttpCache after. OutputCache caches the entire rendered HTML,
> >HttpCache.Insert/Add only chunks of data (in other words you still need
to
> >render the output).
> OK, that's not such a huge problem, it's only a case of pulling it from
> the cache and writing it out.
> I was more thinking about the issue of how long objects live in the
> cache. If I put them in myself, won't they stay there until the cache
> gets full? Also, I'm assuming that when objects get dropped form the
> cache, the least recently used ones will go first. If so, then the HTML
> for the most frequently accessed pages will stay in the cache the
> longest, giving the best performance increase.
> If I understand the OutputCache right, objects will only stay in the
> cache for the time specified. That way, even the frequently accessed
> bits will be dropped. This sounds less efficient.
> Or have I got it completely wrong ;-)
> Thanks for the reply. Any further info would be greatly appreciated.
> --
> Alan Silver
> (anything added below this line is nothing to do with me)
>Alan:
>I wouldn't say one will last in the cache longer than the other. HttpCache
>can also have a time to stay in cache (either as an absolute or a "from last
>access"). So in that sense you have more control. I wouldn't make any
>assumptions about how/when items are dumped from the cache for two reasons.
>First it's probably complicated. Second you shoulnd't assume it's in the
>cache technically (ie, it isn't guaranteed to be there, so you need to write
>the code to get it form the store if it isn't). Having said that, you can
>specify the Priority with HttpCache, again giving you more control, but
>adding to the complexity of what/when will be dropped. I would expect a
>number of factors to play into the decision, such as priority, time last
>used, size, frequency of use, available memory, ....
>if you are worried about the duration of output cache, put it as 86400 (a
>day)... There's no doubt though that HttpCache provides more flexibility
>(priority, absolute vs relative time, dependencies (big one)).

Thanks for the advice. Maybe I'll just write the code as a custom
control with the OutputCache directive and let .NET handle the hard work
for me!! I can always look at optimising the caching later. From what
you say it sounds like OutputCache is a better option (assuming that
this is what you mean by HttpCache), so I'll use that.

Thanks again

--
Alan Silver
(anything added below this line is nothing to do with me)

Please advise about caching

Hello,
I tried out using the cache the other day and was impressed with the
concept. I built myself a custom control to generate the site links,
using an XML file for the info. I kept the XML file in the cache and
added a dependency so it will notice when the file changes. All fine so
far.
I was reading last night about using the OutputCache page directive to
store the page in the cache. It seems you can do this for a user control
as well, allowing you to cache part of a page.
So, my question is, which is more appropriate, using the cache manually
or using the OutputCache page directive? Obviously each will have its
uses, but consider the following ...
I have an e-commerce site written in Classic ASP. I am looking to
rewrite it in ASP.NET at some point. One weakness of the existing
version is that product pages are generated dynamically from a database.
I had been looking at a method whereby when the database is updated, the
HTML is created for the product and written to disk, avoiding the
necessity to hit the database each time the page is displayed.
I am now wondering if it would be better to generate the HTML and store
it in the cache. I could either write the part of the page that displays
that product details as a custom control and use OutputCache to cache
that control, or generate the HTML myself and add it manually to the
cache. Either way I would need some mechanism for checking when the
database is updated, but that's a separate issue.
So, any suggestions? Anything to sway me one way or the other?
One factor I would like to consider is the life of an object in the
cache. The OutputCache directive takes a Duration parameter, which means
that come what May, the HTML will be dropped from the cache when it
expires 9if not sooner). If I put it in the cache manually, AFAIK it
will stay there until it gets kicked out for lack of space. Presumably
an object that is called often is less likely to get kicked out, so the
HTML for the most popular products will stay in the cache the longest,
ensuring maximum efficiency. Is this right?
TIA for any comments on this long waffly post ;-)
Alan Silver
(anything added below this line is nothing to do with me)Alan:
Generally I like to use OutputCache whenever possible, and storing things in
the HttpCache after. OutputCache caches the entire rendered HTML,
HttpCache.Insert/Add only chunks of data (in other words you still need to
render the output).
In IIS 6.0, outputcache is automatically hosted in the kernel which makes it
even faster. In 2.0 outputcache will be even more flexible AND allow you to
store it to the file which will let it last forever (if you wanted to).
As far as performance, the closer to the final product you can cache
(outputcache) the better. And while I typically don't harp on performance,
that's the point of caching so...
Karl
--
MY ASP.Net tutorials
http://www.openmymind.net/
"Alan Silver" <alan-silver@.nospam.thanx> wrote in message
news:JLmJ3uERv3CCFwyT@.nospamthankyou.spam...
> Hello,
> I tried out using the cache the other day and was impressed with the
> concept. I built myself a custom control to generate the site links,
> using an XML file for the info. I kept the XML file in the cache and
> added a dependency so it will notice when the file changes. All fine so
> far.
> I was reading last night about using the OutputCache page directive to
> store the page in the cache. It seems you can do this for a user control
> as well, allowing you to cache part of a page.
> So, my question is, which is more appropriate, using the cache manually
> or using the OutputCache page directive? Obviously each will have its
> uses, but consider the following ...
> I have an e-commerce site written in Classic ASP. I am looking to
> rewrite it in ASP.NET at some point. One weakness of the existing
> version is that product pages are generated dynamically from a database.
> I had been looking at a method whereby when the database is updated, the
> HTML is created for the product and written to disk, avoiding the
> necessity to hit the database each time the page is displayed.
> I am now wondering if it would be better to generate the HTML and store
> it in the cache. I could either write the part of the page that displays
> that product details as a custom control and use OutputCache to cache
> that control, or generate the HTML myself and add it manually to the
> cache. Either way I would need some mechanism for checking when the
> database is updated, but that's a separate issue.
> So, any suggestions? Anything to sway me one way or the other?
> One factor I would like to consider is the life of an object in the
> cache. The OutputCache directive takes a Duration parameter, which means
> that come what May, the HTML will be dropped from the cache when it
> expires 9if not sooner). If I put it in the cache manually, AFAIK it
> will stay there until it gets kicked out for lack of space. Presumably
> an object that is called often is less likely to get kicked out, so the
> HTML for the most popular products will stay in the cache the longest,
> ensuring maximum efficiency. Is this right?
> TIA for any comments on this long waffly post ;-)
> --
> Alan Silver
> (anything added below this line is nothing to do with me)
>Alan:
>Generally I like to use OutputCache whenever possible, and storing things i
n
>the HttpCache after. OutputCache caches the entire rendered HTML,
>HttpCache.Insert/Add only chunks of data (in other words you still need to
>render the output).
OK, that's not such a huge problem, it's only a case of pulling it from
the cache and writing it out.
I was more thinking about the issue of how long objects live in the
cache. If I put them in myself, won't they stay there until the cache
gets full? Also, I'm assuming that when objects get dropped form the
cache, the least recently used ones will go first. If so, then the HTML
for the most frequently accessed pages will stay in the cache the
longest, giving the best performance increase.
If I understand the OutputCache right, objects will only stay in the
cache for the time specified. That way, even the frequently accessed
bits will be dropped. This sounds less efficient.
Or have I got it completely wrong ;-)
Thanks for the reply. Any further info would be greatly appreciated.
Alan Silver
(anything added below this line is nothing to do with me)
Alan:
I wouldn't say one will last in the cache longer than the other. HttpCache
can also have a time to stay in cache (either as an absolute or a "from last
access"). So in that sense you have more control. I wouldn't make any
assumptions about how/when items are dumped from the cache for two reasons.
First it's probably complicated. Second you shoulnd't assume it's in the
cache technically (ie, it isn't guaranteed to be there, so you need to write
the code to get it form the store if it isn't). Having said that, you can
specify the Priority with HttpCache, again giving you more control, but
adding to the complexity of what/when will be dropped. I would expect a
number of factors to play into the decision, such as priority, time last
used, size, frequency of use, available memory, ....
if you are worried about the duration of output cache, put it as 86400 (a
day)... There's no doubt though that HttpCache provides more flexibility
(priority, absolute vs relative time, dependencies (big one)).
Karl
MY ASP.Net tutorials
http://www.openmymind.net/
"Alan Silver" <alan-silver@.nospam.thanx> wrote in message
news:MFwoUbGJH5CCFwSE@.nospamthankyou.spam...
in
to
> OK, that's not such a huge problem, it's only a case of pulling it from
> the cache and writing it out.
> I was more thinking about the issue of how long objects live in the
> cache. If I put them in myself, won't they stay there until the cache
> gets full? Also, I'm assuming that when objects get dropped form the
> cache, the least recently used ones will go first. If so, then the HTML
> for the most frequently accessed pages will stay in the cache the
> longest, giving the best performance increase.
> If I understand the OutputCache right, objects will only stay in the
> cache for the time specified. That way, even the frequently accessed
> bits will be dropped. This sounds less efficient.
> Or have I got it completely wrong ;-)
> Thanks for the reply. Any further info would be greatly appreciated.
> --
> Alan Silver
> (anything added below this line is nothing to do with me)
>Alan:
>I wouldn't say one will last in the cache longer than the other. HttpCache
>can also have a time to stay in cache (either as an absolute or a "from las
t
>access"). So in that sense you have more control. I wouldn't make any
>assumptions about how/when items are dumped from the cache for two reasons.
>First it's probably complicated. Second you shoulnd't assume it's in the
>cache technically (ie, it isn't guaranteed to be there, so you need to writ
e
>the code to get it form the store if it isn't). Having said that, you can
>specify the Priority with HttpCache, again giving you more control, but
>adding to the complexity of what/when will be dropped. I would expect a
>number of factors to play into the decision, such as priority, time last
>used, size, frequency of use, available memory, ....
>if you are worried about the duration of output cache, put it as 86400 (a
>day)... There's no doubt though that HttpCache provides more flexibility
>(priority, absolute vs relative time, dependencies (big one)).
Thanks for the advice. Maybe I'll just write the code as a custom
control with the OutputCache directive and let .NET handle the hard work
for me!! I can always look at optimising the caching later. From what
you say it sounds like OutputCache is a better option (assuming that
this is what you mean by HttpCache), so I'll use that.
Thanks again
Alan Silver
(anything added below this line is nothing to do with me)

Please explain what "Empty path has no directory" means with Server.MapPath

Hello,

I have the following line of code in a script...

litMsg.Text = Server.MapPath("/");

where litMsg is an ASP.Net Literal control. When I try and run this
page, I get the error ...

System.ArgumentException: Empty path has no directory.

Anyone any idea what this means? I have used Server.MapPath many times
before without error, I'm not sure why it suddenly stopped working here.

I'm sure I'm missing something blindingly obvious and would be grateful
if anyone could point it out!! TIA.

--
Alan Silver
(anything added below this line is nothing to do with me)IN case it's of any use to anyone, I found out that the problem was
caused by me having the following two lines in Page_Load...

HttpContext myContext = HttpContext.Current;
myContext.RewritePath("/");

I'm not actually sure *why* I had those lines there, they must have been
from something I was doing before. As soon as I removed them, the
Server.MapPath worked fine.

If anyone has an explanation, I would like to hear it ;-)

>Hello,
>I have the following line of code in a script...
>litMsg.Text = Server.MapPath("/");
>where litMsg is an ASP.Net Literal control. When I try and run this
>page, I get the error ...
>System.ArgumentException: Empty path has no directory.
>Anyone any idea what this means? I have used Server.MapPath many times
>before without error, I'm not sure why it suddenly stopped working here.
>I'm sure I'm missing something blindingly obvious and would be grateful
>if anyone could point it out!! TIA.

--
Alan Silver
(anything added below this line is nothing to do with me)

Please explain why AddHandler works in Page_Load, but not Button_C

I need to understand why if I add a control and use AddHandler to connect its
click event, it will work in Page_Load, but not in a Button_Click.

The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear, but
the click event added with AddHandler does not fire.

A control added in Page_Load with an event handler added with AddHandler
works fine.

I have not writted a web app previously and I guess that I do not understand
how dynamically added handlers work (or dont work).

--
John AustinIt has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
*************************************************
Think outside of the box!
*************************************************
"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...

Quote:

Originally Posted by

>I need to understand why if I add a control and use AddHandler to connect
>its
click event, it will work in Page_Load, but not in a Button_Click.
>
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.
>
A control added in Page_Load with an event handler added with AddHandler
works fine.
>
I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).
>
--
John Austin


the key to understanding asp.net is to know that its stateless, and a form
instance is only used for one request. so if you add a link in a button
click, and the user clicks on that link, a new form is built to process that
request. your code must know to add the handler when that happens. usually
you'd store a flag in viewstate or session to known when to add the handler
(you must also re-add the link control).

-- bruce (sqlwork.com)

"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...

Quote:

Originally Posted by

>I need to understand why if I add a control and use AddHandler to connect
>its
click event, it will work in Page_Load, but not in a Button_Click.
>
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.
>
A control added in Page_Load with an event handler added with AddHandler
works fine.
>
I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).
>
--
John Austin


Sorry, but I still don't get it. What I have in mind is a form with 3 states
that would look a bit like google. State 1, you see a textbox and button, you
type a search value and press the button, State 2, a list of search results
is displayed (a table with a LinkButton in each row), you click on the
selected row's LinkButton. State 3, The details about the selected item are
displayed along with a button to go back to state 1.

The database search after state 1 and the insertion of the results and
LinkButtons in the table must take place in the Button's Click event, the
table duly appears with the data and LinkButtons. At the end of state 2, the
LinkButtons cause a post, but no event is fired, also the entire contents of
the table no longer exist - this does not matter as I only want to know the
ID of the button.

Is the idea of linking the dynamically created LinkButtons to an event the
wrong approach? Should I be looking at the request.form(0) value? Or is my
whole approach wrong, am I thinking too much along Windows Forms lines?
--
John Austin

"Cowboy (Gregory A. Beamer)" wrote:

Quote:

Originally Posted by

It has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.
>
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
>
*************************************************
Think outside of the box!
*************************************************
"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...

Quote:

Originally Posted by

I need to understand why if I add a control and use AddHandler to connect
its
click event, it will work in Page_Load, but not in a Button_Click.

The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.

A control added in Page_Load with an event handler added with AddHandler
works fine.

I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).

--
John Austin


>
>
>


Hi John,

First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.

Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:

1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded

Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).

During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)

For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.

Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.

Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:

<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'

Quote:

Originally Posted by

></asp:LinkButton>


</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>

protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}

LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.

I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.

References:

[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Thank you Walter for your excellent reply. Whilst checking request.form(0) in
Page_Load was a work around (after they click, I don't want the table
anyway), the Repeater is a better solution for me as I can use the event
driven methodology that I am used to with Windows Forms applications.

Thanks once again,
--
John Austin

"Walter Wang [MSFT]" wrote:

Quote:

Originally Posted by

Hi John,
>
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
>
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
>
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
>
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
>
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
>
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
>
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
>
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
>
>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'

Quote:

Originally Posted by

</asp:LinkButton>


</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
>
>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
>
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
>
References:
>
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
>
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
>
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
>
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
>
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>


Hello Walter,
The Data Repeater works fine, but thinking further about the issue, it would
make sense for state 1 to build a query string from input criteria and store
the select statement in viewstate so that the Page_Load in state 2 can query
the database and generate results (this means that pressing Back in the
browser from state 3 would re-query the database and include any changes).
This would also avoid my original problem; but when in state 1, the button
press would need to build the query string, change the state to 2 and then
force a reload of the current page. How could I force the page to be re-build
from the Button_Click event?

--
John Austin

"Walter Wang [MSFT]" wrote:

Quote:

Originally Posted by

Hi John,
>
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
>
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
>
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
>
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
>
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
>
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
>
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
>
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
>
>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'

Quote:

Originally Posted by

</asp:LinkButton>


</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
>
>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
>
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
>
References:
>
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
>
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
>
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
>
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
>
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>


Hi John,

See if following code answers your question:

protected void Page_Load(object sender, EventArgs e)
{
RebindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
QueryStatement = "foo sql statement";
RebindData();
}

void RebindData()
{
string sql = QueryStatement;
if (string.IsNullOrEmpty(sql))
{
Repeater1.DataSource = null;
}
else
{
// you need to do sql query in real app; here I'm just
returning a DataTable for test purpose
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
}
Repeater1.DataBind();
}

string QueryStatement
{
get { reutrn ViewState["QueryStatement"] as string; }
set { ViewState["QueryStatement"] = value; }
}

protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}

Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Sorry Walter, putting the creation of the results table in a subroutine is a
far simpler solution - I guess that getting my head round the way web app
work clouded the brain!

Many thanks,

--
John Austin

"Walter Wang [MSFT]" wrote:

Quote:

Originally Posted by

Hi John,
>
See if following code answers your question:
>
protected void Page_Load(object sender, EventArgs e)
{
RebindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
QueryStatement = "foo sql statement";
RebindData();
}
>
void RebindData()
{
string sql = QueryStatement;
if (string.IsNullOrEmpty(sql))
{
Repeater1.DataSource = null;
}
else
{
// you need to do sql query in real app; here I'm just
returning a DataTable for test purpose
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
}
Repeater1.DataBind();
}
>
string QueryStatement
{
get { reutrn ViewState["QueryStatement"] as string; }
set { ViewState["QueryStatement"] = value; }
}
>
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>

Please explain why AddHandler works in Page_Load, but not Button_C

I need to understand why if I add a control and use AddHandler to connect it
s
click event, it will work in Page_Load, but not in a Button_Click.
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear, but
the click event added with AddHandler does not fire.
A control added in Page_Load with an event handler added with AddHandler
works fine.
I have not writted a web app previously and I guess that I do not understand
how dynamically added handlers work (or dont work).
John Austinthe key to understanding asp.net is to know that its stateless, and a form
instance is only used for one request. so if you add a link in a button
click, and the user clicks on that link, a new form is built to process that
request. your code must know to add the handler when that happens. usually
you'd store a flag in viewstate or session to known when to add the handler
(you must also re-add the link control).
-- bruce (sqlwork.com)
"John Austin" <John.Austin@.nospam.nospam> wrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
>I need to understand why if I add a control and use AddHandler to connect
>its
> click event, it will work in Page_Load, but not in a Button_Click.
> The idea is that the user types some data, presses the button, gets a list
> of results (each with a LinkButton) and can then press one of the link
> buttons to get further information. The newly added link buttons appear,
> but
> the click event added with AddHandler does not fire.
> A control added in Page_Load with an event handler added with AddHandler
> works fine.
> I have not writted a web app previously and I guess that I do not
> understand
> how dynamically added handlers work (or dont work).
> --
> John Austin
It has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
****************************************
*********
Think outside of the box!
****************************************
*********
"John Austin" <John.Austin@.nospam.nospam> wrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
>I need to understand why if I add a control and use AddHandler to connect
>its
> click event, it will work in Page_Load, but not in a Button_Click.
> The idea is that the user types some data, presses the button, gets a list
> of results (each with a LinkButton) and can then press one of the link
> buttons to get further information. The newly added link buttons appear,
> but
> the click event added with AddHandler does not fire.
> A control added in Page_Load with an event handler added with AddHandler
> works fine.
> I have not writted a web app previously and I guess that I do not
> understand
> how dynamically added handlers work (or dont work).
> --
> John Austin

Monday, March 26, 2012

Please guys, help me out !

Guys,
I have a very very basic user control which is
txtEmail
txtPassword
btnLogIn
I'm working on flowlayout mode...i created a complete web page...it collects some data from the user...and finally added aSubmit button.. the page is working perfect...when u click Sumit...as we know..the page will be sumitted...then...i added my very very basic user control at the left of the page ( tables and cells and that stuff) ...run the page...click the Sumbit button (that was working one minute ago) and nothig happens...i tried EVERY THING...and nothing happened...i dont know why the button click event is not being fired !!!
everything is ok...the event handler exists...it is wired wiht on click event in intitalize component function...everything everything is Ok
I'm using VS.NET 2003 (ASP.NET 1.1)
Please guys help me asap
Thanks in advancecan you post some code please...
HTML and code behind
Thanks
Leketje
Please check whether you have handles the IsPostBack event.
The User Control
================
HTML
(%@. Control Language="c#" AutoEventWireup="false" Codebehind="Search.ascx.cs" Inherits="Controls.SearchbyName" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %)
(HTML)
(HEAD)
(LINK media="all" href="http://links.10026.com/?link=Controls\ControlsStyles.css" type="text/css" rel="stylesheet")
(/HEAD)
(body)
(form name="frmMain")
(table cellSpacing="0" cellPadding="0")
(tr)
(td)
(TABLE cellSpacing="0" cellPadding="0")
(TR)
(TD style="PADDING-LEFT: 4px" vAlign="top")
(asp:TextBox id="txtEmailAddress" Runat="server" Width="120px" CssClass="SRTextBox")(/asp:TextBox) (/TD)
(/TR)
(tr)
(TD style="PADDING-LEFT: 4px" vAlign="top" align="left")
(asp:TextBox id="txtPassword" Runat="server" Width="60px" CssClass="SRTextBox" TextMode="Password")(/asp:TextBox)
(/TD)
(/TR)
(TR)
(TD class="LeftPanelButton" style="PADDING-LEFT: 38px; PADDING-BOTTOM: 5px" align="right" colSpan="2")
(asp:Button id="btnLogin" Runat="server" Text="Login")(/asp:Button)
(/TD)
(/TR)
(/TABLE)
(/td)
(/tr)
(/table)
(/form)
(/body)
(/HTML)

Code Behind

namespaceMyNameSpace.Controls

{

using System;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

///<summary>

/// Summary description for SearchbyName.

///</summary>

publicclass SearchbyName : System.Web.UI.UserControl

{

protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;

protected System.Web.UI.WebControls.TextBox txtPassword;

protected System.Web.UI.WebControls.Button btnLogin;

protected System.Web.UI.WebControls.TextBox txtEmailAddress;

protected System.Web.UI.WebControls.TextBox txtName;

privatevoid Page_Load(object sender, System.EventArgs e)

{

if(!IsPostBack)

{

}

}

#region Web Form Designer generated code

overrideprotectedvoid OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

///<summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

///</summary>

privatevoid InitializeComponent()

{

this.btnLogin.Click +=new System.EventHandler(this.btnLogin_Click);

this.Load +=new System.EventHandler(this.Page_Load);

}

#endregion

privatevoid btnLogin_Click(object sender, System.EventArgs e)

{

Response.Write("Help me please");

}

}

}

The web page
===========
HTML
(%@. Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm1" %)
(%@. Register TagPrefix="uc1" TagName="Search" src="http://pics.10026.com/?src=Search.ascx" %)
(!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" )
(HTML)
(HEAD)
(title)WebForm1(/title)
(meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1")
(meta name="CODE_LANGUAGE" Content="C#")
(meta name="vs_defaultClientScript" content="JavaScript")
(meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5")
(/HEAD)
(body)
(form id="Form1" method="post" runat="server")
(table)
(tr)
(td)
(uc1:Search id="Search1" runat="server")(/uc1:Search)
(/td)
(/tr)
(tr)
(td)
(asp:Button id="Button1" runat="server" Text="Button")(/asp:Button)
(/td)
(/tr)
(/table)
(/form)
(/body)
(/HTML)

Code Behind

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace WebApplication2

{

///<summary>

/// Summary description for WebForm1.

///</summary>

publicclass WebForm1 : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button Button1;

privatevoid Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

}

#region Web Form Designer generated code

overrideprotectedvoid OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

///<summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

///</summary>

privatevoid InitializeComponent()

{

this.Button1.Click +=new System.EventHandler(this.Button1_Click);

this.Load +=new System.EventHandler(this.Page_Load);

}

#endregion

privatevoid Button1_Click(object sender, System.EventArgs e)

{

}

}

}

================
I'm sorry for that HTML Crap...it seems i cant use the editor here !!!
Thanks in advance


Deepasmi, thanks...but the point is ...there is no post back !!!
i'm not waiting the button to do something and it didnt...no...the event is not fired at all !!
thanks

The reason why your button doesn't work is because you are including the <html> tags in your user control again...
The main idea of a user control is to create a HTML template with code behind to be included in the main page which already contains the <HTML><HEAD><BODY> and <FORM> tags.
Remove those tags in your user control and your button should work again.
Good Luck
Leketje


Thanks...thanks ...thanks :D:D:D...thaks Leketje...i passed more than 10 hours trying everything...again..thanks :)

Saturday, March 24, 2012

Please help Friends how to control maxlength textbox in datagrid

Is there a way to set the maxlength property for a text box in the datagrid.

My database table field size is only 10 chars for first name.

How can i make the user not to enter more tha 10 chars on the front end.

Is there any Max length property i can assign for the text boxes.

I have 4 text boxes in datagrid.

Thank you very much.Hi,

if it is single-line TextBox, you can use its MaxLength property like you normally can.

<asp:TextBox ID="xxx" MaxLength="4"... /
This works even if TextBox is in a DataGrid.
Thanks Joteke, I have the following code triggered when i click edit in the datagrid, then it will show all text boxes etc. where can i place the maxlength="4" property in the following code.

Thank you very much.

< Code >
Sub MyDataGrid_UpdateCommand(s As Object, e As DataGridCommandEventArgs )
Dim conn As SqlConnection
Dim MyCommand As SqlCommand
Dim strConn as string = "server=Rajender;uid=sa;pwd=sa;database=NORTHWIND"
Dim txtFirstName As textbox = E.Item.cells(2).Controls(0)
Dim txtLastName As textbox = E.Item.cells(3).Controls(0)
Dim txtTitle As textbox = E.Item.cells(4).Controls(0)
Dim strUpdateStmt As String
strUpdateStmt =" UPDATE Employees SET" & _
" FirstName =@.Fname, LastName =@.Lname, Title = @.Title " & _
" WHERE EmployeeID = @.EmpID"
conn = New SqlConnection(strConn)
MyCommand = New SqlCommand(strUpdateStmt, conn)
MyCommand.Parameters.Add(New SQLParameter("@.Fname", txtFirstName.text))
MyCommand.Parameters.Add(New SQLParameter("@.Lname", txtLastName.text))
MyCommand.Parameters.Add(New SQLParameter("@.Title", txtTitle.text))
MyCommand.Parameters.Add(New SQLParameter("@.EmpID", e.Item.Cells(1).Text ))
conn.Open()
MyCommand.ExecuteNonQuery()
MyDataGrid.EditItemIndex = -1
conn.close
BindData
End Sub

</ code >
In that case, you could declare EditItemTemplate for the DataGrid (declaratively in asox) in which you set the TextBox's MaxLength.

If you want to do it programmatically, then you'd do it in ItemDataBound method (when ItemType is EditItem)

Wednesday, March 21, 2012

please help i my code

i cannot navigate to the page i specify, why?

<%@dotnet.itags.org. Control Language="vb" AutoEventWireup="false" Codebehind="Search.ascx.vb" Inherits="SilentBookShop.Search" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<FORM method="post" id="frmSearch" name="frmSearch" action="../WebForm1.aspx">
<TABLE id="Table1" style="WIDTH: 174px; HEIGHT: 90px" cellSpacing="1" cellPadding="1" width="174" align="left" bgColor="#6666ff" border="0">
<TR>
<TD style="COLOR: white; FONT-STYLE: italic; HEIGHT: 15px" align="middle" bgColor="#993300" colSpan="1" rowSpan="1">Search</TD>
</TR>
<TR>
<TD style="HEIGHT: 33px"><SELECT style="WIDTH: 133px">
<OPTION value="" selected>--</OPTION>
<OPTION value="Keyword">Keyword</OPTION>
<OPTION value="Title">Title</OPTION>
<OPTION value="Author">Author</OPTION>
<OPTION value="ISBN">ISBN</OPTION>
</SELECT></TD>
</TR>
<TR>
<TD>
<INPUT style="WIDTH: 132px" type="text" id="searchString" name="searchString">
<INPUT style="WIDTH: 30px; HEIGHT: 22px" type="submit" value="GO"></TD>
</TR>
</TABLE>
</FORM
wen i click at the button, it stays on the same page, it won't go to the page i want.

Thanks!It looks like you're missing some "runat=server" attributes in your elements. This could be contributing to the problem.
Hi,

Because the page that you're going to put your control in already has a form and you can't nest forms.
You should use an asp:button, and Redirect or Transfer from the button's click event.
Alternately, your button's client-side click event could set the action of document.forms[0] to ../WebForm1.aspx and submit.
Let me know if this helps.

Please Help Me for single-threaded apartment

I meet this err, Please help me how to do! (ASP.NET)
Thanks all

"Could not instantiate ActiveX control '46faf861-9911-4d2d-8370-e96e96029bc4' because the current thread is not in a single-threaded apartment. "

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Threading.ThreadStateException: Could not instantiate ActiveX control '46faf861-9911-4d2d-8370-e96e96029bc4' because the current thread is not in a single-threaded apartment.

Source Error:

Line 7: <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Line 8:
Line 9: xserver = New AxiMeetNowServer2Lib.AxiMeetNowServer2
Line 10: Me.xserver.Name = "server"
Line 11: Me.xserver.OcxState = CType(GetObject("server.OcxState"), System.Windows.Forms.AxHost.State)

Source File: c:\inetpub\wwwroot\VC\WebForm1.aspx.vb Line: 9

Stack Trace:

[ThreadStateException: Could not instantiate ActiveX control '46faf861-9911-4d2d-8370-e96e96029bc4' because the current thread is not in a single-threaded apartment.]
System.Windows.Forms.AxHost..ctor(String clsid, Int32 flags)
System.Windows.Forms.AxHost..ctor(String clsid)
AxiMeetNowServer2Lib.AxiMeetNowServer2..ctor()
VC.WebForm1.InitializeComponent() in c:\inetpub\wwwroot\VC\WebForm1.aspx.vb:9
VC.WebForm1.Page_Init(Object sender, EventArgs e) in c:\inetpub\wwwroot\VC\WebForm1.aspx.vb:30
System.Web.UI.Control.OnInit(EventArgs e)
System.Web.UI.Control.InitRecursive(Control namingContainer)
System.Web.UI.Page.ProcessRequestMain()

------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573this usually occurs when trying to convert an ASP page to ASP.NET, but you could try this:

in the <@.Page> directive in the HMTL add this:

<%@.Page aspcompat="true" ... %
this adds a compatibitity directive to your page that should allow STA model to function properly.

Friday, March 16, 2012

Please Help me understand how this works......

Hi. I have this code below and wondering what file I need to import to get the pageContentsCell.Controls.Add(control) line to work.

Private Sub Page_Load(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles MyBase.Load,Me.Load' Save DepartmentID from the query string to a variableDim departmentIdAs String = Request.QueryString("departmentID")' Save the search string from the query string to a variableDim searchStringAs String = Request.QueryString("Search")' We need to find out if the ViewCart parameter has been suppliedDim viewCartAs String = Request.QueryString("ViewCart")' Load page contentsIf Not viewCartIs Nothing Then' we display the shopping cartDim controlAs Control control = Page.LoadControl("UserControls/ShoppingCart.ascx") pageContentsCell.Controls.Add(control)ElseIf Not searchStringIs Nothing Then' you're searching the catalogDim controlAs Controlcontrol = Page.LoadControl("UserControls/SearchResults.ascx") pageContentsCell.Controls.Add(control)ElseIf Not departmentIdIs Nothing Then' you're visiting a department or categoryDim controlAs Controlcontrol = Page.LoadControl("UserControls/Catalog.ascx") pageContentsCell.Controls.Add(control)Else' you're on the main pageDim controlAs Controlcontrol = Page.LoadControl("UserControls/FirstPage.ascx") pageContentsCell.Controls.Add(control)End If End Sub Private Sub viewCartButton_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles viewCartButton.Click' Get the query string as a NameValueCollection objectIf Request.QueryString("ViewCart")Is Nothing Then Response.Redirect("default.aspx?ViewCart=1&" & _ Request.QueryString.ToString())End If End Sub
What's the error message you got for the linepageContentsCell.Controls.Add(control)? You may take a look atCreating Custom Web Controls with ASP.NET 2.0

Please help me, and close the darn form!

Hi,
I've been here before and i'm still stuck with the same problem. I just can't close the stupid form.
I'm using microsoft's browser control on my aplication. I can open a new form when i click any link. That works great.

The BIG problem is when the javascript:window.close() is called from any page. The browser control closes, but i get stuck with the form it was on. I just can't close it.

Please help me. I've been to all kind of forums and still haven't found a solution.

Thanks.I think it has something to do with this bug. It looks like the WindowClosing event isn't beeing fired.

Can someone translate this into VB.Net.

http://www.codeproject.com/buglist/iefix.asp

Thanks.
I've never used the WebBrowser control, so I can't help there.

However, here is an onlineC# to VB.NET converter. It will convert the code provided in the article you referenced.

Hope this helps.
I got it. Thanks for your post "SomeNewKid2", but i didn't use that code. To confusing.

I was trying to use the windowclosing event and it didn't work. I found out that it work with the leave handler.
Like this:


Private Sub AxWebBrowser1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles AxWebBrowser1.Leave
Me.Close()
End Sub

This closes the stupid form also.
Stay well.

Please help override property

Hi,
I've never developed in CSharp before and I'm trying to adapt an
existing user control written in CSharp. The user control inherits from
the DataGridColumn. I'd like for one of my controls properties to
override that of the DataGridColumn. Could somebody help with the
syntax? Currently my code for the property is as follows:
public virtual string HeaderStyle
{
get
{
object savedState = null;
savedState = this.ViewState["HeaderStyle"];
if (savedState != null)
{
return (string)savedState;
}
return "";
}
set
{
this.ViewState["HeaderStyle"] = value;
}
}
When I try to compile I get the message 'HeaderStyle hides inherited
member system.web.ui.webcontrols.datagridcolumn.headerstyle. To make
the current member override that implementation, add the override
keyword. Otherwise add the new keyword'. Please could someone confirm
that instead of
public virtual string HeaderStyle
I should have
public overrides string HeaderStyle
Thanks,
PaulI think it should be "override", without the "s".
An "override" is actually a "virtual" but it emphasize that it override
the virtual function declared in one of its base class. The thing is it
makes the purpose clearer, and avoid the case of accidental overriding
when you actually want a new virtual method, and acidentally create a
new virtual method while you actually want to overriding.