03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

Create successful ePaper yourself

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

H<strong>and</strong>-Cod<strong>in</strong>g Data Access Code x 587<br />

C#<br />

if (!str<strong>in</strong>g.IsNullOrEmpty(Request.QueryStr<strong>in</strong>g.Get("Id")))<br />

{<br />

_id = Convert.ToInt32(Request.QueryStr<strong>in</strong>g.Get("Id"));<br />

}<br />

Because this _id variable is assigned a value <strong>in</strong> Page_Load, it can be used to load an exist<strong>in</strong>g item<br />

to display <strong>in</strong> the form, but also to get the item from the database <strong>in</strong> the SaveButton’s Click event<br />

(which you saw earlier).<br />

If there is an ID ( _id is assigned a value other than -1) <strong>and</strong> the page is not posted back, the<br />

code sets up a new PlanetWroxEntities <strong>in</strong>stance <strong>in</strong>side a us<strong>in</strong>g block <strong>and</strong> queries the Review<br />

<strong>in</strong>stance us<strong>in</strong>g the follow<strong>in</strong>g LINQ to Entities query:<br />

<strong>VB</strong>.<strong>NET</strong><br />

Dim review = (From r In myEntities.Reviews<br />

Where r.Id = _id<br />

Select r).S<strong>in</strong>gleOrDefault()<br />

C#<br />

var review = (from r <strong>in</strong> myEntities.Reviews<br />

where r.Id == _id<br />

select r).S<strong>in</strong>gleOrDefault();<br />

Once the Review <strong>in</strong>stance is found <strong>in</strong> the database, its properties are used to prepopulate the form<br />

controls:<br />

<strong>VB</strong>.<strong>NET</strong><br />

If review IsNot Noth<strong>in</strong>g Then<br />

TitleText.Text = review.Title<br />

SummaryText.Text = review.Summary<br />

BodyText.Text = review.Body<br />

GenreList.DataB<strong>in</strong>d()<br />

Dim myItem As ListItem = GenreList.Items.F<strong>in</strong>dByValue(review.GenreId.ToStr<strong>in</strong>g())<br />

If myItem IsNot Noth<strong>in</strong>g Then<br />

myItem.Selected = True<br />

End If<br />

Authorized.Checked = review.Authorized<br />

End If<br />

C#<br />

if (review != null)<br />

{<br />

TitleText.Text = review.Title;<br />

SummaryText.Text = review.Summary;<br />

BodyText.Text = review.Body;<br />

GenreList.DataB<strong>in</strong>d();<br />

ListItem myItem = GenreList.Items.F<strong>in</strong>dByValue(review.GenreId.ToStr<strong>in</strong>g());<br />

if (myItem != null)<br />

{<br />

myItem.Selected = true;<br />

}<br />

Authorized.Checked = review.Authorized;<br />

}

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

Saved successfully!

Ooh no, something went wrong!