08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 3 ■ WEB FORMS WITH <strong>ASP</strong>.<strong>NET</strong> 49<br />

}<br />

}<br />

}<br />

int nR = 0;<br />

if (sOperation == "Add")<br />

nR = nF + nS;<br />

else<br />

nR = nF - nS;<br />

litResult.Text = nR.ToString();<br />

Now when you run your application, enter values into the text boxes, <strong>and</strong> click the<br />

submit button, you’ll see that the value of the operation is loaded into the Literal control<br />

<strong>and</strong> displayed on the page. But the text boxes are then emptied! Why is this<br />

The same reasoning that applied to the <strong>ASP</strong>.<strong>NET</strong> HTML control for the mathematical<br />

results also applies to the text boxes containing the values to be added or subtracted.<br />

<strong>ASP</strong>.<strong>NET</strong> is unaware that your intention was to maintain the control’s view state, <strong>and</strong><br />

indeed, when the page posted back, <strong>ASP</strong>.<strong>NET</strong> very efficiently threw the values to be<br />

added or subtracted away once the page was refreshed.<br />

As before, one solution is to add the runat <strong>and</strong> id attributes to these controls. And<br />

that works. But the best solution to this problem is to use the full-fledged <strong>ASP</strong>.<strong>NET</strong><br />

TextBox controls <strong>and</strong> have <strong>ASP</strong>.<strong>NET</strong> manage their view state for you. Remember, <strong>ASP</strong>.<strong>NET</strong><br />

converts the TextBox controls into HTML input text boxes for you, but the view state<br />

functionality <strong>ASP</strong>.<strong>NET</strong> employs can now be used to maintain their contents as the request<br />

flow passes back <strong>and</strong> forth. The next step is to replace the <strong>ASP</strong>.<strong>NET</strong> HTML text input controls<br />

with <strong>ASP</strong>.<strong>NET</strong> TextBox controls. You can find these on Visual Studio’s St<strong>and</strong>ard<br />

Toolbox tab alongside the Literal control.<br />

Listing 3-7 shows the revised code for the Default.aspx page using controls<br />

instead of HTML controls for the text boxes.<br />

Listing 3-7. Modified Listing for <strong>ASP</strong>.<strong>NET</strong> Text Boxes<br />

<br />

<br />

<br />

<br />

Untitled Page<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!