Datafield = "ShipCountry" Headertext = "Country" readonly = "true" />
<% # Container.DataItem ("shipvia")%>
Itemtemplate>
EditItemTemplate>
asp: templateColumn>
Columns>
ask: DataGrid>
Bind the code of DataGrid:
Sub bindgrid ()
DIM SQL AS STRING = "Select OrderID,
ShipName, ShipCountry, Shipvia from Orders
DIM DA As SqldataAdapter = New SqldataAdapter (SQL, Connstr)
DIM DS AS New DataSet
Da.fill (DS, "Orders")
DataGrid1.datasource = ds.tables ("Orders"). DefaultView
DataGrid1.databind ()
End Sub
The currently edited item is bound to DropDownlist when triggering a DataGrid ItemDatabase. When using the itemDatabase event, check the listitemType of the current project, otherwise you may find that you are using the HeaderItem or other non-applicable project types. Quote the DropDownList control for EditItem. In the following code, I use the cell control set directly (in order to keep the following examples), however, you can use a simple method to specify ID directly to the DROPDOWNLIST control, and use the DataGrid project's FindControl method locate control Quote. Since the DataGrid is bound to the DataTable default view, the element of the view is the DataRowView type, so you can convert the DataItem property of the current project to a DataRowView instance. This way, you can directly reference the fields in DataItem directly by field name. Using this method, save the current value of "ShipVia" into this record and use it to select the corresponding drop-down list item.
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 CURRENTSHIP As String = DRV ("Shipvia")
DIM DDL As DropdownList = _
CType (E.Item.cells (4) .controls (1), DropdownList
DIM SQL AS STRING = _
"Select ShipperID, CompanyName from Shippers Order by ShipperID"
DIM DA As SqldataAdapter = New SqldataAdapter (SQL, Connstr)
DIM DS AS New DataSet
DIM ITEM AS LISTITEM
Da.fill (DS, "Shippers")
DDL.DataSource = DS.TABLES ("shippers"). DefaultView
DDL.DATATEXTFIELD = "CompanyName"
DDL.DataValuefield = "shipperid"
DDL.DATABIND ()
item = ddl.Items.FindByvalue (currentship)
IF not item is nothing kil.selected = true
END IF
End Sub
Finally, write the code that retrieves the currently selected value from the DropDownList, and executes the database update:
Private sub DataGrid1_updateCommand (Byval Source As Object, _
Byval e as system.Web.ui.WebControls.DataGridCommandEventArgs_
Handles DataGrid1.UpdateCommand
DIM DDL As DropdownList = _
CType (E.Item.cells (4) .controls (1), DropdownList
Dim newship as integer = ddl.selectedValue
Dim ORDERID AS INTEGER = INT32.PARS (E.Item.cells (1) .text)
DIM SQL AS STRING = _
"Update Orders Set Shipvia = @ ship where orderid = @ ID"
DIM CONN As SqlConnection = New SqlConnection (Connstr)
DIM CMD AS New Sqlcommand (SQL, CONN)
Cmd.Parameters.Add (New Sqlparameter ("@ ship", newship))
Cmd.Parameters.Add (New Sqlparameter ("@ ID", ORDERID))
Conn.open ()
Cmd.executenonquery ()
CONN.CLOSE ()
DataGrid1.editIndex = -1
Bindgrid ()
End Sub
All columns: DataGridColumn
We review all the parent types of the built-in type type DataGridColumn. (See Figure 1.) It contains properties and methods commonly used in all DataGrid columns. Types with star indicate that you want to use the type of custom column type.
DataGridColumn property
FooterStyle (TableItemStyle) Footertext HeaderImageURL (String) HeadersTyle Headertext (String) ItemStyle (TableItemStyle) Sortexpression Visible DataGridColumn Method
Initialize Initializecell LoadViewState OncolumnChanged SaveViewState TRACKVIEWSTATE
Reusable methods: Create DropDownColumn
First create a new category library in Microsoft® Visual Studio® .NET and name it MycustomColumn. Add a new class DROPDOWNCOLUMN and make sure you add a namespace in your class definition so your initial code is as follows:
Namespace mycustomcolumn
Public Class DropdownColumn
Inherits DataGridColumn
Public DataSource As ICollection
Public DataField As String
Public DataTextField As String
Public DataValuefield As String
END CLASS
End Namespace
I also declare 4 public properties as shown below:
DataSource. It is used to populate DROPDOWNLISTs. Can be anything that implements the ICollection interface. In the example of this article, I use ArrayList and DataView. Datafield. It is the field in the parent DataGrid data source that corresponds to the data selected from the drop-down list. For example, if DataSource contains a status set, DataField will be similar to "Statecode", or you can use the status free naming field in the table. DataTextField. This is the text to be displayed in the drop-down list, or it is not. Datavaluefield. This is the value indicating the special drop-down option. DataValueField is usually an integer value or other code, and DataTextField is a more meaningful text description for users.
Next, override Initializecell, it is a natural event of the DataGrid column. All cells in the column will happen to INITIALIZECELL, which is very similar to the itemcreated events directly using DataGrid. You can use it to manage cell content, such as setting Headertext, add the DropDownList control you will add data. I have added a handler to the cell's DataBinding event, which needs to take different processing based on whether the current is currently editing. Each system.web.ui.control has a DataBinding event. When the data is bind to the control, you can access the underlying data here, this example is the TableCell object in the DataGrid.
Public Overrides Sub Initializecell (Byval Cell As Tablecell, _
Byval columnIndex as integer, _
BYVAL ITEMTYPE AS LISTITEMTYPE)
MyBase.Initializecell (Cell, ColumnIndex, ItemType) Select Case ItemType
Case ListItemType.Header
Cell.Text = Headertext
Case ListItemType.Item, ListItemType.alternatingItem
AddHandler Cell.Database, Addressof ItemDataBinding
Case ListItemType.editItem
AddHandler Cell.Databinding, Addressof EditItAbinding
DIM DDL AS New DropDownList
Cell.Controls.Add (DDL)
End SELECT
End Sub
Next is the ItemDataBinding routine, the routine is triggered when data or alternatingItem in the DataGrid is performed. You need to reference back to TableCell, you can directly convert the "sender" object that is passed to the event, and then use the Tablecell's NamingContainer attribute to reference the current DataGridItem. This can only display the contents of Datafield in plain text format, just like displayed in BoundColumn. Finally, if the user specified by the user does not exist, I will display more friendly error messages for the user, not only the "index beyond range".
Private sub itemdatabase (Byval E AS Object, ByVal E as Eventargs)
DIM Cell as Tablecell = CType (Sender, Tablecell)
DIM DGI As DataGridItem = CType (Cell.namingContainer, DataGridItem)
Try
Cell.Text = DGI.DataItem (Datafield)
Catch Rangeex As IndexOutofRangeException
Throw new Exception ("Specified Datafield Was Not Found.")
Catch Otherex As Exception
Throw new Exception (Otherex.innerexception.tostring)
END TRY
End Sub
Next, write the code of the EditItemDataBinding event. When a row enters the Edit mode, the event will be triggered on our custom column cell. Retrieve the current cell again and insert the DROPDOWNLIST control when the Initializecell method is called. Add an empty project in DropDown to the first option, if the current data in the column does not match any items you choose from the DataSource collection and placed in the list, select this option.
Then, you need to determine the type of the incoming collection. In this case, I will handle two cases: Passing a set of strings through ArrayList, or DataView in the data table, which is constructed by the DATAROWVIEW project. For string data, I will enter a new ListItem and set the value of the pull-up item and the text. Since both cases are the same, only the text is required here. But I will select the corresponding item to make a selection according to the value so as to be consistent with the next example, and the next example will set a separate value attribute. For the DataRowView project, in the previous example, it has been pointed out that DataRowViewInstance ("FieldName") returns an object indicating the data in the field. You can use the same method to retrieve the values you need for DataTextField and DataValueFields. Finally, some exceptions are throwing with common errors encountered when the developer uses columns, such as send invalid field names to the DataField property, or incompatible DataSource type. I have made hardcodes to the abnormal message to be popped, but I hope that you save these messages to a more configurable location in the actual application. For example, if you want to use your application within a global scale, you can save it to your web.config file or resource file. Similarly, you don't have to throw "Data Datafield" exceptions again, because it may have been captured in the ItemDataBinding event before the DataGrid is placed in the "Edit" mode.
Private sub EditItemDataBinding (Byval Sender as Object, _
ByVal e as evenTargs)
DIM Cell as Tablecell = CType (Sender, Tablecell)
DIM DDL As DropdownList = _
CType (Cell.Controls (0), DropDownList
Dim DataSourceItem as Object
DIM ITEM AS LISTITEM
DIM DGI As DataGridItem
'Add an empty option first
DDL.Items.Add (New ListItem (")))
For Each DataSourceItem in Datasource
Select Case DatasourceItem.gettype.tostring
Case "system.string" 'Apply to the ArrayList example
Item = New ListItem (DatasourceItem, DataSourceItem)
DDL.Items.Add (item)
Case "System.Data.DataRowView"
DIM DRV AS DATAROWVIEW = _
CType (DatasourceItem, DataRowView)
item = new_
Listitem (DRV (DRV (DRV (DRV (DataTextField), DRV (DataValuefield))
DDL.Items.Add (item)
Case Else
Throw New Exception ("Invalid DataSource Type.")
End SELECT
NEXT
Try
DGI = CType (Cell.namingContainer, DataGridItem)
item = ddl.Items.FindByValue (DGI.DataITEM (DataField))
Catch Rangeex As IndexOutofRangeException
Throw New Exception ("Specified Datafield Was Not Found.") Catch Otherex As Exception
Throw new Exception (Otherex.innerexception.tostring)
END TRY
IF not item is nothing kil.selected = true
End Sub
Use DropDownColumn
The above is all the code you need to create a DROPDOWNCOLUMN class. Let's take a look at how to use the control in your application. If you are studying at home, but have not yet started, please compile the namespace created above to MyCustomColumn.dll and copy it to the / bin folder of the application you want to experiment. In this example, I created a new web application UsecustomColumn, and add a reference to my / bin directory mycustomcolumn.dll. Add @REGISTER instructions on the top of the ASPX file:
<% @ Register tagprefix = "dggg"
Namespace = "mycustomcolumn"
AskEMBLY = "MyCustomColumn"%>
Note that the new DataGrid column type does not appear in the Visual Studio .Net property generator for DataGrid, so you need to enter the HTML view and add a column declaration. Make sure the DataGrid declaration is located in a group of