Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Hungry Minds - Visual C# Blueprint.pdf
Скачиваний:
120
Добавлен:
12.02.2016
Размер:
9.71 Mб
Скачать

C#

CONFIGURE THE DATAGRID CONTROL

The DataGrid control is one of the richest Web Server

Controls that you have available in the ASP.NET framework.

To access the majority of the DataGrid control’s features, open the Property Builder dialog box. You can choose from among five views: General, Columns, Paging, Format, and Borders. The Property Builder dialog box is essentially a fancy user interface to the Properties dialog box, which is used for configuring all controls. Due to the DataGrid control having so many built-in features, the Property Builder dialog box comes in handy for quick configurations.

Another way you can configure the DataGrid control is the AutoFormat dialog box. The AutoFormat dialog window

is very similar to the auto format capabilities found for tables in Microsoft Word and Excel. The AutoFormat dialog box is a very quick way to format the grid, but you are stuck with a predetermined list of styles.

Both the Property Builder and Auto Format dialog boxes are available in the pop-up menu for the DataGrid; you can access the pop-up menu by right-clicking the DataGrid. To familiarize yourself with the DataGrid control’s capabilities, use both of these dialog boxes and make changes to the settings provided. After

you make these changes, go to the HTML for the Web form and notice the changes made to the asp:DataGrid element in your Web form.

CONFIGURE THE DATAGRID CONTROL

Autoformat

3601-X fg1205_06.eps

222 for more

 

Right-click the data grid

 

adding server

and select AutoFormat from

form.

the pop-up menu that

DataGrid

appears.

 

 

data set.

 

 

232 for more binding a data

set.

ACCESSING DATA WITH C# AND ADO.NET 12

You can take the code from the Apply It on page 233 one step further by adding sorting to the columns. To implement sorting, set the

AllowSorting attribute on the DataGrid tag equal to true and map the OnSortCommand to an event handler. When a sort request is made, a page level variable (SortExpression) is updated based on the column that was selected.

Example:

string SortExpression = ""; void Grid_Change(Object sender,

DataGridPageChangedEventArgs e) { dgdTitles.CurrentPageIndex = e.NewPageIndex; BindData(); }

void Sort_Grid(Object sender, DataGridSortCommandEventArgs e) { SortExpression = e.SortExpression.ToString(); BindData(); }

void BindData() {

if (SortExpression == "") SortExpression = "title";

SqlConnection cnPubs = new SqlConnection(

"server=(local);uid=sa;pwd=;database=pubs"); SqlDataAdapter daTitles = new SqlDataAdapter(

"select title, notes, price, pubdate from "

+ "titles order by " + SortExpression, cnPubs);

// Use this Data Adapter for rebinding. }

Professional 1

The AutoFormat dialog box appears.

ˇ Click to select a scheme for your data grid.

Á Click the OK button.

Build and browse the Web page.

Note: See page 220 for more information on building and browsing a Web page.

The data grid appears in the preview window formatted with the scheme selected.

235

C#

INSERT DATA INTO A SQL DATABASE

For .NET applications, you can use the System.Data namespace for inserting data into SQL databases. Using the System.Data namespace allows you to insert into

any database with the same basic code. Switching to another database usually only requires changing the ConnectionString property on the database connection.

A simple way to get new data persisted into a SQL database is by running a SQL insert statement. SQL insert statements allow you to populate a database table with a new row of data that is provided by your application. You can collect new data from the user and dynamically build out a SQL insert.

The basic process of running an insert statement is to first acquire a Connection object so that you can communicate to the database. The key to obtaining a Connection object is to build a connection string that contains the authentication, server, and data catalog information (with other optional information). After a connection is obtained, you can use the connection to obtain a Command object. With the Command object, you can set the CommandText property equal to the insert statement. Then, you can execute the insert statement using one of several execution options. The most likely option to use is the ExecuteNonQuery.

INSERT DATA INTO A SQL DATABASE

the namespace

.

the class name

Main function.

Á Save the file.

Add a SqlConnection variable and initialize the variable with a connection string to your database.

° Add a string variable for the insert command and initialize the string with a SQL statement that will add a row to your table.

If you insert data with the same primary key more than once, you will violate a constraint in the pubs database. If you are running a sample without proper error handling, you will halt/kill the application. To degrade gracefully you should implement exception-handling code in the try/catch/finally blocks.

ACCESSING DATA WITH C# AND ADO.NET 12

Example:

//In the if block change the code to the following

//(to capture exceptions like the primary key already

//exists, which will be the case if you run this

//sample more than once).

SqlCommand cmdTitles = new SqlCommand(sInsertCmd, cnPubs);

try

{

cmdTitles.Connection.Open();

cmdTitles.ExecuteNonQuery();

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

finally

{

cmdTitles.Connection.Close();

}

· Add a SqlCommand variable and use the string with the insert command and the connection created.

Open a connection, execute the query, and close the connection.

Add a message to the console about the SQL statement being executed.

± Set a debug stop.

¡ Click F5 to save, build, and run the console application.

The message about the SQL statement appears.

237

Соседние файлы в папке c#