Creating a Command Object Using Visual Studio .NET To create a SqlCommand object using Visual Studio .NET VS .NET, you drag a SqlCommand object from the Data tab of the Toolbox to your f
Trang 1Creating a Command Object Using Visual Studio NET
To create a SqlCommand object using Visual Studio NET (VS NET), you drag a
SqlCommand object from the Data tab of the Toolbox to your form You can also drag an OleDbCommand object from the Data tab of the Toolbox to your form
Before you perform the procedure explained in this section, do the following:
1 Create a new project named MyDataReader containing a Windows application
see how to add a SqlConnection object using VS NET) This object will have the default name of sqlConnection1
3 Configure your sqlConnection1 object to access your Northwind database
object This object is assigned the default name of sqlCommand1
Figure 8.1: A SqlCommand object in a form
You then set the Connection property for your sqlCommand1 using the drop-down list to the right of the Connection property in the Properties window You can select an existing Connection object from the drop-down list; you can also create a new Connection object
by selecting New from the list For this example, select your existing sqlConnection1
You can use Query Builder to create a SQL statement by clicking on the ellipsis button to the right of the CommandText property, and you can set parameters for a command by clicking the ellipsis button to the right of the Parameters property You'll set the
CommandText property of your SqlCommand object to a SELECT statement that
Trang 2retrieves the CustomerID, CompanyName, and ContactName columns from the
Customers table You'll construct this SELECT statement using Query Builder To get started, click the ellipsis button to the right of the CommandText property for your
SqlCommand object
Add button to add the Customers table to your query Click the Close button to continue
Figure 8.2: Adding the Customers table to the query using the Add Table dialog
Next, you construct your query using Query Builder You select the columns you want to retrieve here Add the CustomerID, CompanyName, and ContactName columns using
Figure 8.3: Adding the CustomerID, CompanyName, and ContactName columns to the query using Query Builder
Trang 3Click the OK button to continue The CommandText property of your SqlCommand object is then set to the SELECT statement you created in Query Builder
Note Save your MyDataReader project by selecting File ➣ Save All You'll see the use