Database Reference
In-Depth Information
because you can't cast a string to an int .
Another problem may occur if a query actually returns multiple rows where you thought it would
return only one. In that case, ExecuteScalar( ) just returns the first row of the result and ignores the
rest. If you use ExecuteScalar( ) , make sure you not only expect but actually get a single value returned.
Executing Commands with Multiple Results
For queries where you're expecting multiple rows and columns to be returned, use the command's
ExecuteReader() method.
ExecuteReader() returns a data reader, an instance of the SqlDataReader class that you'll study in the
next chapter. Data readers have methods that allow you to read successive rows in result sets and
retrieve individual column values.
We'll leave the details of data readers for the next chapter, but for comparison's sake, we'll give a
brief example here of using the ExecuteReader() method to create a SqlDataReader from a command to
display query results.
Try It: Using the ExecuteReader Method
To use the ExecuteReader method, follow these steps:
1. Select the ADO.NET_Command project, right-click, and choose Add
Windows Form. From the opened dialog, make sure Windows Form is selected
and rename Form1.cs to CommandReader.cs . Click OK to add this form to the
ADO.NET_Command project.
2. Select the CommandReader form by clicking the form's title bar, and set the
Size property's Width to 455 and Height to 283.
3. Drag a TextBox control over the form. Select this TextBox control, navigate to
the Properties window, and set the following properties:
Set the Name property to txtReader.
Set the Location property's X to 12 and Y to 12.
Set the Multiline property to True.
Set the ScrollBars property to Vertical.
Set the Size property's Width to 415 and Height to 223.
Leave the Text property blank.
4. Now your CommandReader form in the Design view should like Figure 13-5.
 
Search WWH ::




Custom Search