Including a dropdownlistbox in an editable DataGrid...

Source: Internet
Author: User

 

By: John kilgo Date: February 1, 2003 download the code. Printer friendly version

The data choices for some database table columns are relatively fixed. examples wocould be countries, States, and counties for instance. in these cases a dropdown list of fixed choices makes more sense than keyboard input where mistakes can be made easily. in an editable DataGrid you can include dropdownlistboxes, although they must be populated at run time. you cannot do it at design time. in order to accomodate the dropdownlistbox the DataGrid must use templatecolumns with itemtemplates.

For this article I have chosen to present selected data from the northwind customers table. The data between desCountryColumn that is perfect for presentation with a dropdownlistbox when in edit mode.

As is usually the case in dotnetjohn articles, we will separate code from presentation by Using An ASPX page with. VB code-behind page. the ASPX page is presented first. the first part of the page, presented below, just defines our DataGrid. there is nothing unusual about the design of the DataGrid should t that we setup for oneditcommand, onupdatecommand, and oncancelcommad event handlers. these are necessary for any DataGrid to be placed in edit mode. the actual event handlers will be in our code-behind page.

<% @ Page Language = "VB" src = "datagriddropdown. aspx. VB" inherits = "datagriddropdown" %>
<HTML>
<Head>
<Title> DataGrid with a dropdownlistbox </title>
</Head>
<Body>
<Form runat = "server" id = "form1">
<H3> DataGrid with a dropdownlistbox <Asp: DataGrid id = "dtgcustomers" runat = "server"
Autogeneratecolumns = false
Headerstyle-backcolor = "indianred"
Headerstyle-font-bold = "true"
Headerstyle-font-name = "verdana"
Headerstyle-font-size = "12px"
Headerstyle-forecolor = "white"
Itemstyle-backcolor = gainsboro
Itemstyle-font-name = "verdana"
Itemstyle-font-size = "12px"
Oncancelcommand = "dtgcustomers_cancel"
Oneditcommand = "dtgcustomers_edit"
Onupdatecommand = "dtgcustomers_update"
Width = "75%">

Next comes our templatecolumns. we use ASP: labels to hold data for presentation. all of this is pretty straight forward until we come to the Code marked in blue. in the first few lines we have our itemtemplate wherein the country will be shown when the DataGrid is in presentation mode (I. e. not in edit mode ). in this respect it is just like all of the other columns in the grid. we then include a label with its visible property set to false. this invisible label holds the customerid column. it is not needed for presentation but will be needed as a key field for our WHERE clause when updating the row. it cocould have been encoded elsewhere in the grid, but logically belongs with the section where data will be updated. (for purposes of this Article only the country column will be updateable, although all columns cocould have been eligible for update .) notice that we have made arrangements to present the country in two different places. the first is for normal presentation mode, while the second is so that we can see the existing value while we are in edit mode with the dropdownlistbox showing.

Finally comes our dropdownlist box. it is made ready by the line: datasource = "<% # bindthecountry () %> ". while we cannot populate the dropdown at design time, We can reference a function (bindthecountry () that will fill the dropdown at run time. bindthecountry () will be seen in the code-behind page.

<Columns>
<Asp: editcommandcolumn edittext = "edit"
Canceltext = "cancel"
Updatetext = "Update"
Itemstyle-width = "100px"
Headertext = "commands"/>

<Asp: templatecolumn headertext = "company name">
<Itemtemplate>
<Asp: Label id = "lblcompanyname"
TEXT = '<% # databinder. eval (container. dataitem, "companyName") %>'
Runat = "server"/>
</Itemtemplate>
</ASP: templatecolumn>

<Asp: templatecolumn headertext = "contact name">
<Itemtemplate>
<Asp: Label id = "lblcontactname"
TEXT = '<% # databinder. eval (container. dataitem, "contactname") %>'
Runat = "server"/>
</Itemtemplate>
</ASP: templatecolumn>

<Asp: templatecolumn headertext = "Contact title">
<Itemtemplate>
<Asp: Label id = "lblcontacttitle"
TEXT = '<% # databinder. eval (container. dataitem, "contacttitle") %>'
Runat = "server"/>
</Itemtemplate>
</ASP: templatecolumn>

<Asp: templatecolumn headertext = "country">
<Itemtemplate>
<Asp: Label id = "lblcountry"
TEXT = '<% # databinder. eval (container. dataitem, "country") %>'
Runat = "server"/>
</Itemtemplate>
<Edititemtemplate>
<Asp: Label runat = "server"
Id = "lblcustomerid"
Visible = "false"
TEXT = '<% # databinder. eval (container. dataitem, "customerid") %>'/>
<Asp: Label id = "lbltempstate"
TEXT = '<% # databinder. eval (container. dataitem, "country") %>'
Runat = "server"/>
<Asp: dropdownlist id = "ddlcountry"
Datasource = "<% # bindthecountry () %>"
Onprerender = "setdropdownindex"
Datatextfield = "country"
Datavaluefield = "country"
Runat = "server"/>
</Edititemtemplate>
</ASP: templatecolumn>

<Asp: templatecolumn headertext = "telephone">
<Itemtemplate>
<Asp: Label id = "lblphone"
TEXT = '<% # databinder. eval (container. dataitem, "phone") %>'
Runat = "server"/>
</Itemtemplate>
</ASP: templatecolumn>

</Columns>
</ASP: DataGrid>
</Form>
</Body>
</Html>

The remainder of the code above completes the layout of our DataGrid.

Next is our code-behind file where all the work gets done. much of the Code is the usual database access code to populate the DataGrid. the Code immediately below contains the page_load event where the grid is first bound to its data, the bindthegrid () routine to actually accomplish the grid's databinding, the Edit event handler to place the grid in edit mode, and the cancel event handler to get the grid out of edit mode without specify Ming an update. these are necessary routines for any DataGrid being presented, and placed in edit mode.

Please note: In. ASPX page and in both sections of the Code-behind file being shown here, the lines displayed in purple constitue code that allows the dropdownlist to have the current country value preselected when the grid is placed in edit mode. this code was contributed by Victor rubba after this article was originally published. I wish to thank Victor for his contribution.

Imports system
Imports system. Web. UI
Imports system. Web. UI. webcontrols
Imports system. Configuration
Imports system. Data
Imports system. Data. sqlclient

Public class datagriddropdown: inherits page

Protected withevents dtgcustomers as system. Web. UI. webcontrols. DataGrid
Protected strcountry as string
Private sub page_load (byval sender as system. Object, byval e as system. eventargs) handles mybase. Load
If not page. ispostback then
Bindthegrid ()
End if
End sub

Public sub bindthegrid ()
Dim objconn as sqlconnection = new sqlconnection (configurationsettings. etettings ("connectionstring "))
Dim orders customers as sqlcommand = new sqlcommand ("select top 10 mermerid ,"_
& "CompanyName, contactname, contacttitle, country, phone "_
& "From MERs", objconn)

Export customers. commandtype = commandtype. Text
Objconn. open ()
Dtgcustomers. datasource = custom MERs. executereader ()
Dtgcustomers. databind ()
Objconn. Close ()
End sub

Sub dtgcustomers_edit (byval sender as object, byval e as datagridcommandeventargs)
Strcountry = ctype (E. Item. findcontrol ("lblcountry"), label). Text
Dtgcustomers. edititemindex = CINT (E. Item. itemindex)
Bindthegrid ()
End sub

Public sub dtgcustomers_cancel (byval sender as object, byval e as datagridcommandeventargs)
Dtgcustomers. edititemindex =-1
Bindthegrid ()
End sub

The last three routines, shown below, contain the code to populate our dropdownlistbox, to update the table, and to preselect the existing country in the dropdownlist. remember on our ASPX page we cocould not populate the dropdownlistbox, But we cocould make room for it and call a function that wocould populate it at runtime? Bindthecountry () is shown first below. bindthecountry () connects to a database table and executes a reader which is returned to the ASPX page as the dropdownlistbox's data source. normally we wocould access a codes table containing countries. since such a table was not easily available to me, I just did a select distinct country from the customer's table to have something with which to populate the dropdownlistbox.

Sub dtgcustomers_update does the updating of the MERs table with the country value selected from the dropdownlistbox. notice that we must use the findcontrol method to locate the dropdownlist box (ddlcountry) and then get the selecteditem. value property to find the actual country selected from the dropdown. we also use the hidden label on the DataGrid (mentioned in the aspx file discussion) to obtain the customerid column to use as a key field in our WHERE clause for the update.

Public Function bindthecountry ()
Dim objconn as sqlconnection = new sqlconnection (configurationsettings. etettings ("connectionstring "))
Dim orders customers as sqlcommand = new sqlcommand ("select distinct country from customers", objconn)

Export customers. commandtype = commandtype. Text
Objconn. open ()
Return cmdmers. executereader (commandbehavior. closeconnection)
End Function

Public sub dtgcustomers_update (byval sender as object, byval e as datagridcommandeventargs)
Dim objconn as sqlconnection = new sqlconnection (configurationsettings. etettings ("connectionstring "))
Dim extends customers as sqlcommand
Dim strcustomerid as string = ctype (E. Item. findcontrol ("lblblmerid"), label). Text
Dim strcountry as string = ctype (E. Item. findcontrol ("ddlcountry"), dropdownlist). selecteditem. Value
Dim strsql as string

Strsql = "Update MERs set Country = '" & strcountry _
& "'Where mermerid = '" & strcustomerid &"'"
Export MERs = new sqlcommand (strsql, objconn)
Objconn. open ()
Cmdmers. executereader (commandbehavior. closeconnection)
Dtgcustomers. edititemindex =-1
Bindthegrid ()
End sub

Public sub setdropdownindex (byval sender as object, byval e as system. eventargs)
Dim ed as system. Web. UI. webcontrols. dropdownlist
Ed = sender
Ed. selectedindex = ed. Items. indexof (ed. Items. findbytext (strcountry ))
End sub

End Class

A fair amount of code has been presented, but I believe if you will run the demo program several times to see how the editing works in the grid, and then compare what you see to the varous sections of code, you will come away with an understanding of how the process works.

Once again, thanks to Victor rubba for his code contributions (listed in purple) for this article.

You may run the program here.
You may download the code here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.