Frequently Asked Questions for DataGrid Web Server Control

xiaoxiao2021-03-06  36

Author: Visual Studio Team Microsoft Corporation

January 2002

Summary: Answer common issues using the DataGrid Web Server Control. (22 pages of 22)

Applicable Products

Microsoft® Visual Studio® .NET ASP.NET Web Form DataGrid Web Server Control

content

Windows Form VS. Web Form DataGrid Control Data Row Width, Height and Alignment Self-Order Display and Edit Mode Date, Money and Other Data Dynamic Display and Hide Data Operations Add to Data Row Using DataGrid Control Items Add a new record to the data source in editing mode Show a drop-down list Use the verification block to select multiple items (Hotmail model) once edited multiple information column to select the information column

Introduction

The DataGrid Web Server Control Item is a powerful tool for displaying the information source. It is easy to use. As long as you set a few properties, you can display editable information in a professional appearance. Moreover, the checkered object model provides a large amount of data display.

This document will answer news groups, websites, websites, and other developer discussion regions, the relevant questions displayed by the book, the techniques described in the document are very simple, some complicated, but no matter which case, Cross the basic features of the DataGrid control item, let you have a deeper understanding.

This article assumes that you are already familiar with the control item, know how to add the control item to your form, set it to display the information. You should also learn how to turn the data columns in the square into edit mode, as well as other basic work (for more information, see <

DataGrid Web Server Control

>). Finally, if you know how to handle the sample (join the template data line to the square, configure the control item in the template), there will be a lot of help.

Windows Form vs. Web Form DataGrid Control

The equivalent control items of the Web Form DataGrid control item and Windows Form are not the same, and everyone is usually assumed (this is a reasonable hypothesis) These two control items are the same, or at least the same function. However, the entire program model and Windows Form's entire programming example and Windows Form are large. For example, any processing of the web form page performs a round trip of the server, which must be managed, and the data series model is different.

Due to these differences, their various control items have great differences, including DataGrid control items. Generally speaking, the Built-in function of the Web Form DataGrid control is small.

It itself does not support the main - detailed information structure. Like other web server controls, it does not support two-way information, and if you want to update your information, you must write a code code. You can only edit a piece of information at a time. Although it causes events to process it, it is not supported in order to sort checkered content.

on the other hand:

You can serve Web Form DataGrid to support

Ienumerable

Any item of the interface. Web Form DataGrid Control Item Support Patement. Compared with Windows Form, the appearance and configuration of the Self-binding Web Form DataGrid control items is easy (detailed information later).

Control data line width, height and alignment

According to the preset, the DataGrid control will adjust the data line and the information column to make it best suggest to the entire height and width of the specified. It will be preset to the left according to the width of the data line header text in the entire checkered width.

To control the characteristics of the data, you must set the AutoGenerateColumns property to false and turn off the automatic data line. In fact, only in short-term use (such as a quick concept certificate page or demonstration), it is necessary to set this property to true. If it is actually implemented, you should explicitly join the data line; the individual data line can be a line of assembly or Model data line. To set the data line width, you have to create a style item of the data line, and then set the Width property of the project to a standard unit (for example, pixels). The following example shows the HTML syntax of the ItemStyle project seting the width property.

Headeertext = "Title">

Or, like the examples, set the itemStyle property directly in the project, perform the same work:

Sortexpression = "title" Headeertext = "Title">

You can use the style item to set alignment, set it to "Right", "Left", and Horizontalalign lists other values ​​defined in the type (Visual Studio, you can align in the [format] index tag of the character generator Individual information line). The following is an example:

Headeertext = "Title">

You can also set the height of the data line using the style item (or ItemStyle-HEIGHT property). You may find that this is not as resilient as a width, because the height of setting a line will set the height of all data lines at the same time.

You can also set the width in the Run Time. For example, ItemCreated events can be set. The following example will set the width of the first two data to 100 and 50 pixels, respectively:

'Visual Basic

Private sub DataGrid1_itemcreated (byval sender as object, _

Byval e as system.web.ui.webcontrols.DataGriditeMeventArgs_

Handles DataGrid1.Itemcreated

E.Item.cells (0) .width = new unit (100)

E.Item.cells (1) .width = new unit (50)

End Sub

// C #

Private void DataGrid1_itemcreated (Object Sender, System.Web.ui.WebControls.DataGriditeMeventArgs E)

{

E.Item.cells [0] .width = new unit (100); E.Item.cells [1] .width = new unit (50);

}

Of course, the fixed width can be set in the design phase, and if it is set in the program code, there is not much significance. It is usually only to do when you want to set the width according to the Run Time value. You can use the unit (usually pixel) to set the width of the storage, but to convert the data length (purely the character count) into pixels, but in this case, when establishing a project, there is information Check.

Data line configuration in self-order display and editing mode

According to the preset, the box will display the information line in a predetermined size. When you switch some information, the control item will display all editable text blocks regardless of the information of the information.

If you want to book the content of the information, you will turn the data line into a model line, its role is like the project template in the DataList or Repeater control, but you define the configuration of the data line (rather than information column). .

When defining the model line, you can specify the following model type:

ItemTemplate allows you to customize the normal display of your information. EditItemTemplate allows you to specify that the data column is switched to edit mode, which is displayed in the data line, which in addition to the specified preset text block, allows you to specify the control item to edit. HeadeRTemplate and Footertemplate have allow you to make your own headers and page (only when the checkered ShowFooter property is TRUE).

The following example demonstrates HTML syntax of the model of Bubin value information. ItemTemplate and EditItemplate are displayed using a verification block, and the clicking in the itemtemplate will be deactivated, allowing the user to not verify, and the NGP is enabled in EditItemTemplate.

ID = "CheckBox2"

Checked = '<% # DataBinder.eval (Container, "DataItem.discontinued")%>>>

Runat = "server" name = "checkbox2" id = "checkbox2"

Checked = '<% # DataBinder.eval (Container, "DataItem.discontinued")%>>>

Note if you are

Used in EditItemTemplate

Checkbox control item, please understand that in the Run Time, the Fang Follower is actually included in addition to the cord of squares.

LITERALCONTROL control item (control spacing). As long as you know the value and identification code of the control item, use the FindControl method to build its reference, not to use

Cells and

Specific index in the Controls collection:

'Visual Basic

DIM CB As Checkbox

CB = CType (E.Item.FindControl ("Checkbox2"), Checkbox)

// C #

Checkbox CB;

CB = (Checkbox) E.Item.FindControl ("CheckBox2");

In Visual Studio, you can use the checkered properties generator to establish a sample line and use the protocol editor to specify the configuration. Select the data line from the [Data Line] index tab of the checkered [Properties] window page, press [Change this information to the model line]. Close [Properties] Window, press the right mouse button in the checkered, then select [Edit Mode]. Then you can drag the control item from the toolbox to the template and add static text.

Format date, currency and other information

The information in the DataGrid Control will be displayed in the HTML table of the Web Form page, so to control the display mode of the data, you can specify the NET string format of the data line value. You can only specify the format of the line or the model line, and cannot specify the format of the data line generated when the checkered autogeneratecolumns property is set to True.

To format, set the DataFormatString property of the data to the appropriate string formatted operation of the information that is appropriate to format. The format string is slightly confused, and the same specified element (such as "D") will produce different results if they are set to different data types (integers, date).

Note that in Visual Studio, you can specify a format operation in the [Data Line] index tab of the control item attribute generator.

The following table lists some example formatted strings. For more information, see the Visual Studio file.

>with

> Etc.

Format The model applies to the data: {0: C}

Note {0} is zero, not letter O.

Numerical / Ten Ground Displays the value of "Price:", the number of currency formats. The currency format is set depending on the cultural settings specified by the cultural attributes in the web.config file. {0: D4} integer (cannot be used in conjunction with the decimal number.) Integer is displayed in the zero fill field of four cells wide. {0: N2}% value shows the number of 2 digits, and then the rest value is "%". {0: 000.0} Value / Ten Grounds to a small number of numbers. A number of less than three digits will be filled with zero. {0: D} Date / Date Time Date Format ("Thursday, August 06, 1996). The date format is set depending on the cultural setting of the page or web.config file. {0: D} Date / Date Time Short Date Format ("12/31/99"). {0: YY-mm-DD} Date / Date Time Digital Year - Month - Date of Japanese Format (96-08-06).

Dynamic display and hidden information

One of the ways to make information line dynamically display is to establish a data line in the design phase, and again, you need to hide or display these data, which can be done using the Visible property of the setting data line. The following example demonstrates how to switch to the second data line in the checkered (INDEX 1):

'Visual Basic

DataGrid1.columns (1) .visible = NOT (DataGrid1.columns (1) .visible)

// C #

DataGrid1.columns [1] .visible =! (DataGrid1.columns [1] .visible);

Dynamic joining information

If you know the required information in advance, you can decide to hide or display the information line, but sometimes you will know when Run Time will know, at this time, you can dynamically establish a line, add it to the checkered. You can establish a piece of information on a piece of data (BOUNDCOLUMN, EDITCOMMANDCOLUMN, ButtonColumn, or HyperLinkColumn) (you can join the square data line, but this will be slightly complicated. For details, please see < Create a web server control items>), set the properties of the data line, and add it to the checkered ColumnS collection.

The following example shows how to join both lines of junctions.

'Visual Basic

Private sub button1_click (byval sender as system.Object, _

Byval e as system.eventargs) Handles Button1.click

'Setting the quaint data tunature

DataGrid1.autogeneratecolumns = false

DataGrid1.datasource = me.dsbooks1

DataGrid1.DataMember = "Books"

DataGrid1.DataKeyfield = "BookID"

'Join two data

DIM DGC_ID AS New BoundColumn ()

DGC_ID.Datafield = "BookID"

DGC_ID.Headertext = "Identification"

DGC_ID.ItemStyle.Width = New Unit (80)

DataGrid1.columns.add (DGC_ID)

DIM DGC_TITLE AS New BoundColumn ()

DGC_Title.Datafield = "Title"

DGC_TILE.HEADERTEXT = "Title"

DataGrid1.columns.add (dgc_title)

Me.sqldataAdapter1.fill (me.dsbooks1)

DataGrid1.databind ()

End Sub

// C #

Private void Button1_Click (Object Sender, System.Eventargs E)

{

DataGrid1.autogeneratecolumns = false;

DataGrid1.datasource = this.dsbooks1;

DataGrid1.DataMember = "books";

DataGrid1.DataKeyfield = "BookID";

// Join two data lines

BoundColumn DGC_ID = new boundcolumn ();

DGC_ID.Datafield = "BookID";

DGC_ID.Headertext = "Identification Code";

DGC_ID.ItemStyle.Width = New Unit (80);

DataGrid1.columns.add (DGC_ID);

BoundColumn DGC_Title = new boundcolumn ();

DGC_TITLE.DATAFIELD = "Title";

DGC_TILE.HEADERTEXT = "Title";

DataGrid1.columns.add (dgc_title);

THIS.SQLDATAADAPTER1.FILL (this.dsbooks1); DataGrid1.DATABIND ();

}

There will be a problem of saving in any time when the control item is dynamically added to a web page. Dynamically added control items (or the data lines in this example) do not automatically join the webpage, so you must add logic to the web page, and determine that the data line is available every round trip.

The best way is to overwrite the LoadViewState method of the web page, allowing you to re-establish the data in the DataGrid control. Since the LoadViewState method is called before the Page_Load event is triggered, and therefore re-adds the data line in the LoadViewState method, you can ensure that these data can be handled normally when any event program is executed.

The following example shows how to expand the previous example, restore the information on each re-execute the web page. As in front, the Button1_Click handling current will join two data lines in the checkered (in this example, the event handling Customer calls another common form "of AddColumns to perform this job). In addition, the web also contains a simple cloth attribute called DynamicColumnsadded, indicating whether the checkered data is added. This attribute will maintain its value in the inspection state. The LoadViewState method first calls the LoadViewState method of the substrate category, which is uncompressed to check status information and set its control. If the data line has previously joined the square (using the DynamicColumnsadded property), the method will re-join these data.

'Visual Basic

Private property DynamicColumnAdded () as boolean

Get

IF ViewState ("ColumnAdded") Is Nothing Then

Return False

Else

Return True

END IF

END GET

Set (ByVal Value As Boolean)

ViewState ("ColumnAdded") = Value

End set

End Property

Protected Overrides Sub LoadViewState (Byval SavedState As Object)

Mybase.loadviewState (SavedState)

If Me. DynamicColumnAdded Then

Me.AddColums ()

END IF

End Sub

Private sub button1_click (byvale as system.object, byval e as system.eventargs) Handles Button1.click

'Check the properties, determine that the data is not repeated

If Me. DynamicColumnAdded Then

Return

Else

Me.AddColums ()

END IF

End Sub

Protected sub addcolums ()

'Join two data

DIM DGC_ID AS New BoundColumn ()

DGC_ID.Datafield = "Instock"

DGC_ID.Headertext = "Spot Supply?"

DGC_ID.ItemStyle.Width = New Unit (80)

DataGrid1.columns.add (DGC_ID)

DIM DGC_TITLE AS New BoundColumn ()

DGC_Title.Datafield = "Title"

DGC_TILE.HEADERTEXT = "Title"

DataGrid1.columns.add (dgc_title) me.dataGrid1.database ()

Me. DynamicColumnAdded = TRUE

End Sub

// C #

Private bool dynamiccolumnadded {

get

{

Object b = viewstate ["DynamicColumnAdded"];

Return (b == null) False: true;

}

set

{

ViewState ["DynamicColumnAdded"] = Value;

}

}

Protected Override Void LoadViewState (Object SavedState)

{

Base.LoadViewState (SavedState);

IF (DynamicColumnAdded)

{

THIS.ADDCOLUMNS ();

}

}

Private void Button1_Click (Object Sender, System.Eventargs E)

{

IF (this. DynamicColumnAdded! = true)

{

THIS.ADDCOLUMNS ();

}

}

Private void addColumns ()

{

BoundColumn DGC_ID = new boundcolumn ();

DGC_ID.Datafield = "BookID";

DGC_ID.Headertext = "Identification Code";

DGC_ID.ItemStyle.Width = New Unit (80);

DataGrid1.columns.add (DGC_ID);

BoundColumn DGC_Title = new boundcolumn ();

DGC_TITLE.DATAFIELD = "Title";

DGC_TILE.HEADERTEXT = "Title";

DataGrid1.columns.add (dgc_title);

THIS.SQLDATAADAPTER1.FILL (THIS.DSBOOKS1);

DataGrid1.databind ();

THIS. DynamicColumnAdded = True;

}

Use the DataGrid control to add new records to the source

The DataGrid control enables users to review and edit records, but it does not contain functions to join new records, however, you can use many ways to join this feature, the main methods are as follows:

In the checkered data source (data set or database), add a new blank record. If necessary, you need to specify the identification code for the record and place an alternate symbol value in any data line that cannot be NULL. Renew the DataGrid control item to the source. Switch the checker to edit mode to edit new records. You must be able to determine the location where the new record appears in the square. Update the record normally after the user presses [Update], thus adding the source with the value provided by the user.

The following example shows the joining new record, set the square, and then switch it to the program of editing mode. In this case, the data source is a data set (DSBooks1 or DSBooks1) containing "BOOKS".

'Visual Basic

Private sub btnaddrow_click (byval sender as system.Object, _

Byval e as system.eventargs) Handles btnaddrow.click

DIM DR AS DATAROW = Me.dsbooks1.books.newrow

DR ("Title" = "(new)" DR ("instock") = true

Me.dsbooks1.books.rows.insertat (DR, 0)

Session ("DSBooks") = dsbooks1

DataGrid1.editIndex = 0

DataGrid1.databind ()

End Sub

// C #

Private void btnaddrow_click (Object Sender, System.Eventargs E)

{

DataRow Dr = this.dsbooks1.books.newrow ();

DR ["Title"] = "(New)";

DR ["Instock"] = TRUE;

this.dsbooks1.books.rows.insertat (DR, 0);

Session ["DSBooks"] = dsbooks1;

DataGrid1.edititemindex = 0;

DataGrid1.databind ();

}

Pay attention to a few points:

This program code will be executed after the user presses the [Add] button on the web page. The new information column is built using the new way, and then insert it into the data set information sheet with the insertat method, and you can put it in a predefined specific location, in this example, the first pen in the data sheet Record (that is, the first record in the ROWS collection). Alternatively, it can also add it to the end of the data sheet and use the data list count as a value. Importantly, you fully know the location of the information list in the information sheet. Because you know that the record is in the first location in the data table, you can set the checkered edititeMindex value to zero, switch the new data column to edit mode (if you establish a data column in other locations in the data table, you can EditIndex is converted to this location). Since there is a new record in the data (but not in the database), there must be a copy of the data set between round-trips. After all, you don't want to re-filled from the database to cause loss of new records. The program code is stored here as a working phase state. When web is loaded, you must reload the data set from the working phase status. The following example shows your Page_Load handling a common style: 'Visual Basic

Private sub page_load (byval sender as system.Object, _

BYVAL E as system.eventargs) Handles mybase.load

IF me.ispostback then

DSBooks1 = CType (Session ("DSBooks"), DSBooks

Else

Me.sqldataAdapter1.fill (me.dsbooks1)

Session ("DSBooks") = dsbooks1

DataGrid1.databind ()

END IF

End Sub

// C #

Private Void Page_Load (Object Sender, System.EventArgs E)

{

IF (this.ispostback)

{

DSBooks1 = (DSBooks) session ["dsbooks"];

}

Else

{

THIS.SQLDATAADAPTER1.FILL (THIS.DSBOOKS1);

Session ["DSBooks"] = dsbooks1;

THIS.DATAGRID1.DATABIND ();

}

} For information on maintenance status, see

". You can update your record normally. For example, see the Visual Studio file.

". After updating the information set, please update the database, then reintertify the information set, you must store the rearranged data set to the working phase status. The following is an example of updating process: 'Visual Basic

Private sub DataGrid1_updateCommand (Byval Source As Object, _

Byval e as system.Web.ui.WebControls.DataGridCommandEventArgs_

Handles DataGrid1.UpdateCommand

DIM DR AS DATASET.BOOKSROW

'References of getting a column (inserted by the information column)

DR = me.dsbooks1.books (0)

DIM TB As TextBox = CType (E.Item.cells (2) .controls (0), Textbox)

Dr.title = tb.text

DIM CB As Checkbox = CType (E.Item.cells (3) .controls (1), Checkbox)

Dr.instock = cb.checked

Me.sqldataAdapter1.Update (me.dsbooks1)

DataGrid1.editIndex = -1

Return the information set from the database

DSBooks1.clear ()

Me.sqldataAdapter1.fill (me.dsbooks1)

'Reissue the data set to be reinited into a working stage status

Session ("DSBooks") = dsbooks1

DataGrid1.databind ()

End Sub

// C #

Private void DataGrid1_UpdateCommand (Object Source, System.Web.ui.WebControls.DataGridCommandeventArgs E)

{

DSBOOKS.BOOKSROW DR;

/ / Take the reference of the column (inserted by the insertion list)

Dr = this.dsbooks1.books [0];

Textbox TB1 = (TextBox) E.Item.cells [2] .controls [0];

Dr.title = tb1.text;

Checkbox CB = (Checkbox) E.Item.cells [3] .controls [1];

Dr.instock = cb.checked;

This.sqldataAdapter1.Update (this.dsbooks1);

DataGrid1.edititemindex = -1;

/ / Realize the information from the database

DSBooks1.clear ();

THIS.SQLDATAADAPTER1.FILL (THIS.DSBOOKS1);

// Re-organized the data set to the working stage status

Session ["DSBooks"] = dsbooks1;

DataGrid1.databind ();

}

Display a drop-down list in edit mode

The data column is a common requirement to display the drop-down list when processing editing mode. For example, checkered may display a list of books, including the type of each book. When the user edits book records, you may have to specify different types. Ideally, they can choose from the display of possible type values ​​(such as "novel", "biography" or "reference book").

To display a drop-down list, there must be a template data in the square. Tymmert, ItemTemplate contains a control item (such as a data set Label control item) to display a value current value in the record, and then add a drop-down list to EditItemTemplate. In Visual Studio, you can add the sample data line in the Cement property generator, then use the standard template editor to remove the preset TextBox control item from EditItemTemplate, and drag a DROPDOWNLIST control item. Alternatively, the sample data can be added to the HTML view. After establishing a row of samples including a drop-down list, there are two works. The first item is to fill in the list, the second item is to select the appropriate item in the list, for example, if the type of book is set to "Fiction", you usually want to display the "Fiction" in advance when the drop-down list is selected (in all Under the case, there will be no problem in pre-selecting a project).

Many ways to fill in the drop-down list, the following example only introduces three ways: use static items; use the records in the data; or use the data reader to read information directly from the database.

Static project

To display static items in the drop-down list, do not make the control items, as long as the item is defined in the Items collection of the control item. In Visual Studio, you can use the items collection from the [Properties] window. Alternatively, you can join the item in the HTML view.

The following is a display type in display mode, and the full profile of the model of the type of static list of static lists in Edit mode is defined. ItemTemplate contains a Label control entry, which is a TEXT property to the currently recorded "Type" field. The static project declaration in EditItemTemplate will emphasize.

Text = '<% # DataBinder.eval (Container, "DataItem.genre")%>'>

Novel

Biography

Reference

Data set

If the information you want to display in the drop-down list is in the data set, you can use the general data to be tied. The following is shown below is a declarative syntax. DROPDOWNLIST controls are set to the type data sheet named DSBooks1. The data set setting will emphasize.

Text = '<% # DataBinder.eval (Container, "DataItem.genre")%>'>

DataSource = "<% # dsbooks1%>" DataMember = "genre"

DataTextField = "genre" DataValuefield = "genre" width = "160px">

Information reader

You can also fill in the drop-down list directly from the database, which is more complicated, but the efficiency is high because you only read the data from the database when you need it.

A relatively simple method is to use the Web Form data tuning role. Although the DataBinder.eval method is mostly calling in the data system junction, you can actually call any public members available for webpages. This example will demonstrate how to create a DataTable object that establishes, fills in, and backlink a list of DataTable objects.

In this case, you must be able to perform the information command you want. For example, you may define a CommandText property of the information command for select * from Genres. To simplify examples, assume that there is already a connection item and a data command item on your webpage.

The first is to create a public function in the web page, which creates a data sheet, and defines the information you need. Then turn on the connection, execute the information command to return the data reader, and copy the information to the information sheet through the reader loop. Finally, the data sheet is transmitted back to the feed value of the function.

The following example shows the way the execution, only one data line ("Genre") in this example of this example. You usually only need a data line when you fill in a drop-down list.

'Visual Basic

Public Function GetgenRetable () AS DataTable

DIM DTGENRE AS DATATABLE = New DataTable ()

IF Application ("Genretable") Is Nothing Then

DIM DR AS DATAROW

DIM DC AS New Datacolumn ("Genre")

DTGENRE.COLUMNS.ADD (DC)

Me.sqlConnection1.Open ()

DIM DREADER As Sqlclient.sqlDataReader = _

Me.sqlcommand1.executeReader ()

While Dreader.read ()

Dr = dtgenre.newrow ()

DR (0) = DREADER (0)

DTgenre.Rows.Add (DR)

End while

Me.sqlConnection1.close ()

Else

DTGENRE = CTYPE (Application ("GenRetable", DataTable) End IF

Return DTGENRE

END FUNCTION

// c #

Public DataTable getgenretable ()

{

DataTable dtgenre = new datatable ();

IF (Application ["Genretable"] == NULL)

{

DataRow DR;

Datacolumn DC = New Datacolumn ("Genre");

DTGENRE.COLUMNS.ADD (DC);

THIS.SQLCONNECTION1.OPEN ();

System.data.sqlclient.sqldataReader DREADER =

This.sqlcommand1.executeReader ();

While (DREADER.READ ())

{

DR = dtgenre.newrow ();

DR [0] = DREADER [0];

DTgenre.Rows.Add (DR);

}

THIS.SQLCONNECTION1.CLOSE ();

}

Else

{

DTGENRE = (DataTable) Application ["genretable"];

}

Return DTgenre; E

}

Please note that the form of information is created quickly to the application status. Since the data sheet is a static check-in table, you don't have to re-read the data sheet each time you have different data columns to switch to edit mode. In addition, because multiple users can use the same information table, you can get taking in the whole country application, rather than getting better in the user-specific working phase.

The following shows the announcement of the model data line. You will see that this is very similar to the grammar used by the data set data sheet, the only real difference is that the DataSource service will call your function. This technology has a small disadvantage that it is impossible to get too much design assistance in Visual Studio. Since you are defined in the program, Visual Studio cannot provide any options set by DataMember, DataTextField, and DataValueField properties. You have to make sure to set these properties to the name of the member created in the program code.

Text = '<% # DataBinder.eval (Container, "DataItem.genre")%>'>

DataSource = "<% # getgenretable ()%>"

DataMember = "genre"

DataTextField = "genre"

DataValuefield = "genre"

Width = "120px">

Pre-selecting items in the drop-down list

You tend to set the items selected in the drop-down list to match the specific value, usually the value displayed in the storage grid in the display mode. It is to set the value of the drop-down list SelectDex property to the index of the value to display.

The following example shows a reliable method set in the ItemDatabase on the DataGrid project. This is the correct event that should be used, because regardless of the source of the drop-down list, it guarantees that the pull-down list is already completed.

The trick is to know what value to set the drop-down list. Usually the current project, or the current data DataITEM property (back to the DATAROWVIEW object containing current record) has provided you with this value. Once you have a value, you can use the DropDownList control of the FindByText or FindByValue method to find the correct item in the list; you can then use the project's indexof property to return the index.

'Visual Basic

Private sub DataGrid1_itemdatabase (Byval Sender As Object, _

Byval e as system.web.ui.webcontrols.DataGriditeMeventArgs_

Handles DataGrid1.ItemDatabase

If E.Item.ItemType = ListItemType.editItem Then

DIM DRV AS DATAROWVIEW = CTYPE (E.Item.DataItem, DataRowView)

DIM Currentgenre As String = CType (DRV ("Genre"), String)

DIM DDL As DropdownList

DDL = ctype (E.Item.FindControl ("DropdownList1"), DROPDOWNLIST)

Ddl.selectedIndex = DDL.Items.indexof (DDL.Items.FindBytext (currentgenre))

END IF

End Sub

// C #

Private void DataGrid1_itemdatabase (Object Sender, System.Web.ui.WebControls.DataGriditeMeventArgs E)

{

IF (E.Item.ItemType == ListItemType.editItem) {

DataRowView DRV = (DATAROWVIEW) E.Item.DataItem;

String currentgenre = DRV ["genre"]. TOSTRING ();

DropDownList DDL =

(DROPDOWNLIST) E.Item.FindControl ("DropDownList1");

DDL.SelectedIndex =

Ddl.Items.indexof (DDL.Items.FindBytext (currentgenre);

}

}

Use the Nuclear Square to select multiple items (Hotmail model)

In Microsoft Hotmail® and other applications, users can verify the blocks in "Select" multiple data columns, then perform jobs for all selected data columns - such as all delete or all copies.

To join this type of feature, add a template line in the checkered, then place the verification block in the data line. When the web page is executed, the user can check the items you want to use.

To actually execute the user action, you can move the checkered items collection, check the appropriate information line (storage grid), see if the verification is verified. The following example shows how you can delete the data columns corresponding to the items that the user checks. We assume that the DSBooks1 information set contains the Books Data Sheet. 'Visual Basic

Private sub btndelete_click (Byval Sender as system.Object, _

Byval e as system.eventargs) Handles btndelete.click

'Touch the checkered list

DIM I as integer = 0

DIM CB As Checkbox

DIM DGI As DataGridItem

Dim bookid as integer

DIM DR AS DSBOOKS.BOOKSROW

For Each DGI in DataGrid1.Items

CB = ctype (DGI.cells (0) .controls (1), Checkbox)

IF cb.checked then

'Decide the index key of the selected record ...

Bookid = ctype (DataGrid1.DataKeys (i), integer

'... to obtain the indicator of the records records..

DR = me.dsbooks1.books.findbybookid (bookid)

'... and delete it.

Dr.delete ()

END IF

i = 1

NEXT

Me.sqldataAdapter1.Update (dsbooks1)

Me.sqldataAdapter1.Fill (dsbooks1)

DataGrid1.databind ()

End Sub

// C #

Private void btndelete_click (Object Sender, System.Eventargs E)

{

INT i = 0;

Checkbox CB;

Int bookid;

DSBOOKS.BOOKSROW DR;

Foreach (DataGridItem DGI in this.DataGrid1.Items)

{

CB = (Checkbox) DGI.cells [0] .controls [1];

IF (cb.checked)

{

/ / Decide the index key of the selected record ...

Bookid = (int) DataGrid1.DataKeys [i];

// ... get the indicator of the corresponding information collection ...

Dr = this.dsbooks1.books.findbybookid (bookid);

// ... and delete it.

Dr.delete ();

}

i ;

}

This.sqldataAdapter1.Update (this.dsbooks1);

THIS.SQLDATAADAPTER1.FILL (THIS.DSBOOKS1);

DataGrid1.databind ();

}

There are a few things to pay attention to:

You can use the standard method of acquiring the control item value from the model line, and determine if the verification block has been selected - the item is obtained from the storage grid's Controls collection and appropriately converts. If you get the checkbox control, remember that this is usually the second control item (INDEX 1) because it has a regular control item (even if it is blank). If it is deleted, you should follow the index key, not the displacement in the data set. The index of a project in the DataGrid Control is not necessarily consistent with the index of the same record in the data sheet. Even if you consistent, wait until the first record is deleted. The program code takes the record index key from the checkered DataKey collection. Then find the records you want to delete using the FindBy method in the data collection table. After deleting records from the data set (strictly just marked as deleted), you call the UPDATE method of the data contractor to remove it from the database. Then, the program is reinited from the database and re-serves. Edit multiple data columns

The standard method of editing the data column in the DataGrid control (add [edit, update, cancel] button to the checkered data line) only allows the user to edit a data column once. If the user wants to edit multiple data columns, press the [Edit] button to make changes, then press the [Update] button for each column.

Sometimes, the settings are a very practical alternative to the preset to edit mode. In this case, the checkered information will be displayed in the text block or other control; the user does not have to clear the checker to edit mode. Typically, the user will make the change they want, and then press a button (not the buttons in the checker), and all changes are sent at a time. The web page looks like the picture below:

[figure 1]

No matter where you are processing the data set, or use the information command to process the data source, any information model can use this editing square style.

To set the checkered in multiple columns, please join the data line as usual, then convert all editable data lines to the template data line. Select the data line in the [Data Line] index tab of the square property generator, then select [Translate this data to the template data line from the bottom side of the window]. To edit the model, press the right button in the checkered, then select [Edit Sample].

Add editing controls to ItemTemplate. Note that because the data column is not displayed in editing mode, you don't add it to EditItemTemplate as usual. That is, ItemTemplate will contain an editable control.

Set the squeezing of the square as usual. You must individually provide each editable control. Typical data lines are like this:

DataBinder.eval (Container, "DataItem.title")

Loading the square is normal. But update is a bit different, because when you use the [Update] button, you must browse the entire checkered, update all the information columns.

The following example shows a possibility. In this case, you assume that you use the DCMDuPdateBooks that contain parameterized SQL Update statements. The program code will expand the value from the editable control items in the square, and then specify the value to the command parameter. Then perform a data command for each square item.

'Visual Basic

Private sub btnupdate_click (Byval E AS System.EventArgs) Handles btnupdate.click

DIM I as integer

DIM DGI As DataGridItem

Dim bookid as integer

Dim TextBoxTitle As Textbox

Dim CheckboxInstock As Checkbox

Dim TextBoxPrice As Textbox

Dim labelbookid as labelfor i = 0 to data - 1.Items.count - 1

DGI = DataGrid1.Items (i)

Labelbookid = ctype (dgi.cells (0) .controls (1), label

Bookid = ctype (labelbookid.text, integer)

TextBoxTitle = CType (DGI.FindControl ("TextBoxTitle"), TextBox

CheckboxInstock = _

CType (DGI.FindControl ("CheckBoxInstock", Checkbox)

TextBoxPrice = CType (DGI.FindControl ("TextBoxPrice"), TextBox)

Me.dcmdupdateBooks.Parameters ("@ Bookid"). Value = BookId

Me.dcmdupdatebooks.Parameters ("@ title"). Value = TextBoxTitle.Text

Me.dcmdupdateBooks.Parameters ("@ instock"). Value = checkboxinstock.checked

Me.dcmdupdatebooks.Parameters ("@ price"). Value = textBoxPrice.Text

Me.sqlConnection1.Open ()

Me.dcmdupdateBooks.executenonQuery ()

Me.sqlConnection1.close ()

NEXT

End Sub

// C #

Private void btnupdate_click (Object Sender, System.Eventargs E)

{

INT I;

DataGridItem DGI;

Int bookid;

Textbox textboxTitle;

Checkbox checkboxinstock;

Textbox textBoxprice;

For (i = 0; i <= DataGrid1.items.count -1; i )

{

DGI = DataGrid1.items [i];

Label labelbookid = (label) Dgi.cells [0] .controls [1];

Bookid = int.parse (labelbookid.text);

TextBoxTitle = (TextBox) DGI.FindControl ("TextboxTitle");

CheckBoxInstock = (Checkbox) DGI.FindControl ("CheckBoxInstock");

TextBoxPrice = (TextBox) DGI.FindControl ("TextBoxPrice");

This.dcmdupdatebooks.Parameters ["@ Bookid"]. value = bookid;

This.dcmdupdatebooks.Parameters ["@ Title"]. Value = textboxtitle.Text;

This.dcmdupdatebooks.Parameters ["@ instock"]. Value = checkboxinstock.checked;

This.dcmdupdatebooks.Parameters ["@ price"]. Value = float.parse (THSQLCONNECTION1.Open ();

THIS.DCMDUPDATEBOOKS.EXECUTENONQUERY ();

THIS.SQLCONNECTION1.CLOSE ();

}

}

Check the changed item

The update policy described above has a disadvantage. If there is only a small amount of change, it is not efficient to transmit every checkered data column to the data set or database. If you are using the information set, you can join logic, check the changes between the control items in the square and the data set in the data set column. If not using the information set - just like the example above - it is easy to compare, because it is involved in the reticle of the database.

There is a strategy for both sources of information, which is to establish a method of judging whether the data column is "changed" to check before updating. The most reliable method that determines whether the data column has changed is to process the changed event of the control item in the data column. For example, if your checkered information is included in the TEXTBOX control, you can respond to the TextChanged event of the control. If it is a verification of the square, it can also respond to the CheckedChanged event.

You have maintained a list of information columns to update in the processing of these events. Usually, the best strategy is to track the main index key of the affected information column. For example, you can maintain an ArrayList object that contains the list of information to be updated.

Imagine the above example follows this strategy. Establish an autograph of an ArrayList object as a member of the web category:

'Visual Basic

Protected bookidlist as arraylist = new arraylist ()

// C #

Protected arraylist bookidlist = new arraylist ();

Then establish a process of processing, as long as the control item is changed, the book identification code is added to the ArrayList object. The following code shows that the TEXTBOX control entries triggers its TextChanged event or checkbox control, however, can be used when it causes its CheckedChanged event:

'Visual Basic

Protected Sub Rowchanged (Byval Sender As Object, _

ByVal e as system.eventargs)

DIM DGI As DataGridItem = _

Ctype (CType (Sender, Control) .namingContainer, DataGridItem)

Dim Bookidlabel as label = ctype (DGI.cells (0) .controls (1), Label

Dim bookid as integer = ctype (BookidLabel.Text, Integer)

IF not (BookidList.Contains) THEN

BookidList.Add (Bookid)

END IF

End Sub

// C #

Protected Void Rowchanged (Object Sender, System.EventArgs E)

{

DataGridItem DGI = (DataGridItem) ((Control) Sender .namingContainer;

Label bookidlabel = (label) DGI.cells [0] .controls [1];

INT bookid = int.parse (BookidLabel.Text);

IF (! bookidlist.contains) {

BookidList.Add (Bookid);

}

}

Note that the method cannot be private, otherwise it will not be able to be junctioned to this method later.

Understanding the change event preset is helping to post the webpage back to the server. The event will only be raised when you post the web page (usually through the Click event). When processing a web page, the webpage and its control items will initialize and then trigger all change events. Control Item Click events that are posted only after the process of processing of change events is caused.

The rowchanged method described above. The program code must obtain a book identification code from the current project. Event will not pass the project to you (many DataGrid events are passed), so you must turn back. The NamingContainer property is obtained from the sender quotes of the event (the square item), then cut down to obtain the Label control item value of the display book identification code.

You must check that there is no book identification in the array. Each control item in the data column will individually trigger an event, so if multiple control items have changed, the book identification code may be added multiple times.

The change event of the control item is always triggered and processed before the Click event. Therefore, you can use the array list in the change event, and determine that the button event processing in the post form will be used (in this case BTNUPDATE_CLICK handler) to execute.

With the list of array, you can slide a slightly modify the process of handling the management update. In btnUpdate_click, when you repeat your data, you can add a test to see if the current book identification code is in the array list. If so, update.

'Visual Basic

Private sub btnupdate_click (Byval Sender as system.Object, _

Byval e as system.eventargs) Handles btnUpdate.click

DIM I as integer

DIM DGI As DataGridItem

'Other announcements

For i = 0 to DataGrid1.Items.count - 1

DGI = DataGrid1.Items (i)

Labelbookid = ctype (dgi.cells (0) .controls (1), label

IF BookidList.Contains (Bookid) THEN

TextBoxTitle = CType (DGI.FindControl ("TextBoxTitle"), TextBox

'Other update program

END IF

NEXT

End Sub

// C #

Private void btnupdate_click (Object Sender, System.Eventargs E)

{

INT I;

DataGridItem DGI;

Int bookid;

// Other announcements

For (i = 0; i <= DataGrid1.items.count -1; i )

{

DGI = DataGrid1.items [i];

Tablecell TC = DGI.Cells [0];

String s = dgi.cells [0] .TEXT;

Label labelbookid = (label) Dgi.cells [0] .controls [1];

Bookid = int.parse (labelbookid.text);

IF (BookidList.Contains (BookID))

{

/ / Update Procedure

}

}

}

There is still one thing left: Treatment of a commonly tiered to the control item event. In Visual Studio, you can only perform this job in the HTML view. The control item does not explicitly perform individualization in the Code-Behind file, so it is not supported by the program tool. Switch the .aspx file to HTML review, add the following emphasis on each control item:

ID = textboxtitle runat = "server"

Text = '<% # DataBinder.eval (Container, "DataItem.title")%>'>

Runat = "server"

Checked = '<% # databinder.eval (Container, "DataItem.instock")%>>

The TEXTBOX and CHECKBOX controls can call the same method from their respective change methods because the two events handle the common signature. If you have a clear order or drop-down list of control items, its SELECTEDEXCHANGED event also passes the same quotes, the same situation.

Select information columns anywhere

The model for selecting the data column in the square is to let you join the CommandName property set to "Select" [Picking] button (actually a LinkButton control item). When the button is pressed, the DataGrid control will receive the selected command and automatically display the data column in the selected mode.

Not everyone likes to have a display [selection] button, and the common problem is how to actually, so that the user can select the information column at any of the checkered data column. The answer is to play some small tricks in the square. You can still use the button if you are using the [Selection] LinkButton control item. You can also hide the button. No matter which event, you are inserted into some user-end instruction codes that effectively repeat the functionality of the [Selection] button in the web page.

The following example shows how to do it. In a square ItemDatabase, you can first determine that you are not in the header, page or page inspection area, then get a reference for the [Selection] button, in this case, it is assumed to be the first storage grid A control item. Then you call the well-known GetPostBackClienthyPERLINK method. This method passes back the repositor's repositor with the specified control item. In other words, if you pass the reference to the LinkButton control item, it will pass back the name of the user-ended call that will perform a post.

Finally, you specify the user-end method for the project itself. When the square is presented, it will be presented as an HTML form. The method is specified to the project, which is equal to each of the data columns ( item) in the data sheet to join the user's terms. Checkered ITEM objects do not directly support it to specify the user's terms, but you can use its Attributes collection to do this, this collection will pass any of the content you specify to the browser. Note that this technique has a small disadvantage, which is to add some content to the data stream presenting to the browser, and the information of each data column is added to the viewing status.

'Visual Basic

Private sub DataGrid1_itemdatabase (Byval Sender As Object, _

Byval e as system.web.ui.webcontrols.DataGriditeMeventArgs_

Handles DataGrid1.ItemDatabase

DIM ITEMTYPE As ListItemType = E.Item.ItemType

IF (itemType = ListItemType.Pager) OR_

(itemtype = listitemtype.header) OR_

(itemtype = listitemtype.footer).

Return

Else

Dim Button as linkbutton = _

CType (E.Item.cells (0) .controls (0), LinkButton

E.Item.attributes ("onclick" = _

Page.GetPostBackClienthyperLink (Button, "")

END IF

End Sub

// C #

Private void DataGrid1_itemdatabase (Object Sender, System.Web.ui.WebControls.DataGriditeMeventArgs E)

{

ListitemType ItemType = E.Item.ItemType;

IF (itemType == ListItemType.pager) ||

(itemtype == ListiteMTYPE.HEADER) ||

(itemtype == ListiteMType.footer))

{

Return;

}

LinkButton Button = (LinkButton) E.Item.cells [0] .controls [0];

E.Item.attributes ["onclick] =

Page.GetPostBackClienthyPerlink (Button, ");

}

转载请注明原文地址:https://www.9cbs.com/read-60214.html

New Post(0)