0% found this document useful (0 votes)
92 views27 pages

ASP.NET GridView Radio Buttons

This document provides instructions for enhancing a GridView control to include a column of radio buttons for row selection. It describes adding necessary pages and configuring an ObjectDataSource to populate the GridView with supplier data from the USA. While adding a radio button to each row via a TemplateField allows single selection, the buttons are not mutually exclusive. The next steps explain how to properly group the radio buttons to allow only one selection at a time.

Uploaded by

Abhi Basak
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views27 pages

ASP.NET GridView Radio Buttons

This document provides instructions for enhancing a GridView control to include a column of radio buttons for row selection. It describes adding necessary pages and configuring an ObjectDataSource to populate the GridView with supplier data from the USA. While adding a radio button to each row via a TemplateField allows single selection, the buttons are not mutually exclusive. The next steps explain how to properly group the radio buttons to allow only one selection at a time.

Uploaded by

Abhi Basak
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] [Link][Link]

WorkingwithDatainASP.NET2.0::Addinga GridViewColumnofRadioButtons Introduction


[Link] displayingtext,images,hyperlinks,[Link] ofthemouse,itspossibletomakeaGridViewwhereeachrowcanbeselectedviaabutton,ortoenableeditingor [Link],therewilloftenbesituationsinwhichadditional, [Link] GridViewsfunctionalitytoincludeadditionalfeatures. [Link]/Detail UsingaSelectableMasterGridViewwithaDetailsDetailView,wecanaddaCommandFieldtotheGridViewthat [Link],apostbackensuesandtheGridViewsSelectedIndex propertyisupdated [Link]/DetailUsingaSelectableMasterGridView withaDetailsDetailView tutorial,wesawhowtousethisfeaturetodisplaydetailsfortheselectedGridViewrow. WhiletheSelectbuttonworksinmanysituations,[Link], twootheruserinterfaceelementsarecommonlyusedforselection:[Link] augmenttheGridViewsothatinsteadofaSelectbutton,[Link] scenarioswheretheusercanonlyselectoneoftheGridViewrecords,theradiobuttonmightbepreferredoverthe [Link] application,whereausermightwanttoselectmultiplemessagestodelete thecheckboxoffersfunctionalitythat isnotavailablefromtheSelectbuttonorradiobuttonuserinterfaces. [Link] checkboxes.

Step1:CreatingtheEnhancingtheGridViewWebPages
BeforewestartenhancingtheGridViewtoincludeacolumnofradiobuttons,letsfirsttakeamomenttocreatethe [Link] [Link],[Link],makingsuretoassociate [Link] masterpage:
[Link] [Link] l [Link] l [Link]
l l

1 of27

Figure1:[Link]

Likeintheotherfolders,[Link] intheEnhancedGridView [Link] [Link] [Link],addthisUser [Link] bydraggingitfromtheSolutionExplorerontothepagesDesignview.

2 of27

Figure2:[Link] UserControlto [Link]

Lastly,[Link] [Link],addthefollowingmarkupafterthe UsingtheSqlDataSourceControl<siteMapNode>:


<siteMapNode title="EnhancingtheGridView" url="~/EnhancedGridView/[Link]" description="AugmenttheuserexperienceoftheGridViewcontrol."> <siteMapNode url="~/EnhancedGridView/[Link]" title="SelectionviaaRadioButtonColumn" description="ExplorehowtoaddacolumnofradiobuttonsintheGridView."/> <siteMapNode url="~/EnhancedGridView/[Link]" title="SelectionviaaCheckboxColumn" description="SelectmultiplerecordsintheGridViewbyusingacolumnof checkboxes."/> <siteMapNode url="~/EnhancedGridView/[Link]" title="AddNewRecordsthroughtheFooter" description="Learnhowtoallowuserstoaddnewrecordsthroughthe GridView'sfooter."/> </siteMapNode>

3 of27

[Link],[Link] nowincludesitemsfortheediting,inserting,anddeletingtutorials.

Figure3:TheSiteMapNowIncludesEntriesfortheEnhancingtheGridViewTutorials

Step2:DisplayingtheSuppliersinaGridView
ForthistutorialletsbuildaGridViewthatliststhesuppliersfromtheUSA,witheachGridViewrowprovidinga [Link],theusercanviewthesuppliersproductsbyclickinga [Link],[Link] wedelveintothesesubtleties,letsfirstgetaGridViewlistingthesuppliers. [Link] pageintheEnhancedGridView folderbydraggingaGridView [Link] toSuppliers and,fromitssmarttag,choosetocreate [Link],createanObjectDataSourcenamedSuppliersDataSource thatpullsitsdatafrom theSuppliersBLL object.

4 of27

Figure4:CreateaNewObjectDataSourceNamed SuppliersDataSource

5 of27

Figure5:ConfiguretheObjectDataSourcetoUsetheSuppliersBLL Class

SinceweonlywanttolistthosesuppliersintheUSA,choosetheGetSuppliersByCountry(country) method fromthedropdownlistintheSELECTtab.

6 of27

Figure6:ConfiguretheObjectDataSourcetoUsetheSuppliersBLL Class

FromtheUPDATEtab,selectthe(None) optionandclickNext.

7 of27

Figure7:ConfiguretheObjectDataSourcetoUsetheSuppliersBLL Class

SincetheGetSuppliersByCountry(country) methodacceptsaparameter,theConfigureDataSourcewizard [Link](USA, inthisexample),leavethe [Link] wizard.

8 of27

Figure8:UseUSA astheDefaultValueforthecountry Parameter

Aftercompletingthewizard,[Link] allbuttheCompanyName,City,andCountry BoundFields,andrenametheCompanyName BoundFields HeaderText propertytoSupplier. Afterdoingso,theGridViewandObjectDataSourcedeclarativesyntaxshouldlooksimilar tothefollowing.


<asp:GridViewID="Suppliers"runat="server"AutoGenerateColumns="False" DataKeyNames="SupplierID"DataSourceID="SuppliersDataSource" EnableViewState="False"> <Columns> <asp:BoundFieldDataField="CompanyName"HeaderText="Supplier" SortExpression="CompanyName"/> <asp:BoundFieldDataField="City"HeaderText="City" SortExpression="City"/> <asp:BoundFieldDataField="Country"HeaderText="Country" SortExpression="Country"/> </Columns> </asp:GridView> <asp:ObjectDataSourceID="SuppliersDataSource"runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetSuppliersByCountry"TypeName="SuppliersBLL"> <SelectParameters> <asp:ParameterDefaultValue="USA"Name="country"Type="String"/> </SelectParameters> </asp:ObjectDataSource>

9 of27

Forthistutorial,letsallowtheusertoviewtheselectedsuppliersproductsonthesamepageasthesupplierlist, [Link],[Link] twoButtonstoListProducts andSendToProducts,withtheideathatwhenListProducts isclickedapostback willoccurandtheselectedsuppliersproductswillbelistedonthesamepage,butwhenSendToProducts is clicked,theuserwillbewhiskedtoaanotherpagethatliststheproducts. Figure9showstheSuppliers GridViewandthetwoButtonWebcontrolswhenviewedthroughabrowser.

Figure9:ThoseSuppliersfromtheUSAHaveTheirName,City,andCountryInformationListed

Step3:AddingaColumnofRadioButtons
AtthispointtheSuppliers GridViewhasthreeBoundFieldsdisplayingthecompanyname,city,andcountryof [Link],[Link],theGridView doesntincludeabuiltinRadioButtonField,[Link],we canaddaTemplateFieldandconfigureitsItemTemplate torenderaradiobutton,resultinginaradiobuttonfor eachGridViewrow. Initially,wemightassumethatthedesireduserinterfacecanbeimplementedbyaddingaRadioButtonWeb controltotheItemTemplate [Link] theGridView,[Link],anenduseris abletoselectmultipleradiobuttonssimultaneouslyfromtheGridView.

10 of27

EventhoughusingaTemplateFieldofRadioButtonWebcontrolsdoesnotofferthefunctionalityweneed,lets implementthisapproach,[Link] addingaTemplateFieldtotheSuppliersGridView,[Link],fromtheGridViewssmart tag,clicktheEditTemplateslinkanddragaRadioButtonWebcontrolfromtheToolboxintotheTemplateFields ItemTemplate (seeFigure10).SettheRadioButtonsID propertytoRowSelector andtheGroupName propertyto SuppliersGroup.

Figure10:AddaRadioButtonWebControltotheItemTemplate

AftermakingtheseadditionsthroughtheDesigner,yourGridViewsmarkupshouldlooksimilartothefollowing:
<asp:GridViewID="Suppliers"runat="server"AutoGenerateColumns="False" DataKeyNames="SupplierID"DataSourceID="SuppliersDataSource" EnableViewState="False"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:RadioButtonID="RowSelector"runat="server" GroupName="SuppliersGroup"/> </ItemTemplate> </asp:TemplateField> <asp:BoundFieldDataField="CompanyName"HeaderText="Supplier" SortExpression="CompanyName"/> <asp:BoundFieldDataField="City"HeaderText="City" SortExpression="City"/> <asp:BoundFieldDataField="Country"HeaderText="Country"

11 of27

SortExpression="Country"/> </Columns> </asp:GridView>

TheRadioButtonsGroupName [Link] withthesameGroupName valueareconsideredgroupedonlyoneradiobuttoncanbeselectedfromagroupata [Link] propertyspecifiesthevaluefortherenderedradiobuttonsname [Link] examinestheradiobuttonsname attributestodeterminetheradiobuttongroupings. WiththeRadioButtonWebcontroladdedtotheItemTemplate,visitthispagethroughabrowserandclickonthe [Link],makingitpossibletoselectallof therows,asFigure11shows.

Figure11:TheGridViewsRadioButtonsareNotGrouped

Thereasontheradiobuttonsarenotgroupedisbecausetheirrenderedname attributesaredifferent,despitehaving thesameGroupName [Link],doaView/Sourcefromthebrowserandexamine theradiobuttonmarkup:


<inputid="ctl00_MainContent_Suppliers_ctl02_RowSelector" name="ctl00$MainContent$Suppliers$ctl02$SuppliersGroup" type="radio"value="RowSelector"/> <inputid="ctl00_MainContent_Suppliers_ctl03_RowSelector" name="ctl00$MainContent$Suppliers$ctl03$SuppliersGroup" type="radio"value="RowSelector"/> <inputid="ctl00_MainContent_Suppliers_ctl04_RowSelector" name="ctl00$MainContent$Suppliers$ctl04$SuppliersGroup"

12 of27

type="radio"value="RowSelector"/> <inputid="ctl00_MainContent_Suppliers_ctl05_RowSelector" name="ctl00$MainContent$Suppliers$ctl05$SuppliersGroup" type="radio"value="RowSelector"/>

Noticehowboththename andid attributesarenottheexactvaluesasspecifiedinthePropertieswindow,butare prependedwithanumberofotherID [Link] valuesaddedtothefrontoftherenderedid and name attributesaretheIDsoftheradiobuttons parentcontrols the GridViewRowsIDs,theGridViewsID,the ContentcontrolsID,[Link] GridViewhasauniqueid andname values. Eachrenderedcontrolneedsadifferentname andid becausethisishowthebrowseruniquelyidentifieseach controlontheclientsideandhowitidentifiestothewebserverwhatactionorchangehasoccurredonpostback. Forexample,imaginethatwewantedtorunsomeserversidecodewheneveraRadioButtonscheckedstatewas [Link] propertytotrue andcreatingan eventhandlerfortheCheckChanged [Link],iftherenderedname andid valuesforalloftheradiobuttons werethesame,onpostbackwecouldnotdeterminewhatspecificRadioButtonwasclicked. TheshortofitisthatwecannotcreateacolumnofradiobuttonsinaGridViewusingtheRadioButtonWeb [Link],wemustuseratherarchaictechniquestoensurethattheappropriatemarkupisinjectedintoeach GridViewrow. Note:LiketheRadioButtonWebcontrol,theradiobuttonHTMLcontrol,whenaddedtoatemplate,will includetheuniquename attribute,[Link] withHTMLcontrols,feelfreetodisregardthisnote,asHTMLcontrolsarerarelyused,especiallyin [Link],[Link] WebControlsand HTMLControls.

UsingaLiteralControltoInjectRadioButtonMarkup
InordertocorrectlygroupalloftheradiobuttonswithintheGridView,weneedtomanuallyinjecttheradio buttons [Link] name attribute,butshouldhavea uniqueid attribute(incasewewanttoaccessaradiobuttonviaclientsidescript).Afterauserselectsaradio buttonandpostsbackthepage,thebrowserwillsendbackthevalueoftheselectedradiobuttonsvalue attribute. Therefore,eachradiobuttonwillneedauniquevalue [Link],onpostbackweneedtomakesuretoadd thechecked attributetotheoneradiobuttonthatisselected,otherwiseaftertheusermakesaselectionandposts back,theradiobuttonswillreturntotheirdefaultstate(allunselected). [Link] [Link] theUsingTemplateFieldsintheGridViewControl [Link]:
<inputtype="radio"id='<%#GetUniqueRadioButtonID(...)%>' name='SuppliersGroup'value='<%#GetRadioButtonValue(...)%>'.../>

Here,GetUniqueRadioButton andGetRadioButtonValue wouldbemethodsdefinedinthecodebehindclass thatreturnedtheappropriateid andvalue [Link] assigningtheid andvalue attributes,butfallsshortwhenneedingtospecifythechecked attributevaluebecause [Link],iftheGridViewhas viewstateenabled,theformattingmethodswillonlyfirewhenthepageisfirstloaded(orwhentheGridViewis explicitlyreboundtothedatasource),andthereforethefunctionthatsetsthechecked attributewontbecalledon [Link],[Link],however, [Link] 13 of27

anexercisewontgetyouanyclosertoaworkingversion,itwillhelpfosteradeeperunderstandingofthe GridViewandthedatabindinglifecycle. Theotherapproachtoinjectingcustom,lowlevelmarkupinatemplate andtheapproachthatwellbeusingfor thistutorial istoaddaLiteralcontrol [Link],intheGridViewsRowCreated orRowDataBound eventhandler,theLiteralcontrolcanbeprogrammaticallyaccessedanditsText propertysettothemarkupto emit. StartbyremovingtheRadioButtonfromtheTemplateFieldsItemTemplate,[Link] theLiteralcontrolsID toRadioButtonMarkup.

Figure12:AddaLiteralControltotheItemTemplate

Next,createaneventhandlerfortheGridViewsRowCreated [Link] eventfiresonceforevery rowadded,[Link] dataisreloadedfromviewstate,theRowCreated eventstillfiresandthisisthereasonweareusingitinsteadof RowDataBound (whichfiresonlywhenthedataisexplicitlyboundtothedataWebcontrol). Inthiseventhandler,[Link] programmaticallyreferencetheRadioButtonMarkup LiteralcontrolandsetitsText propertytothemarkupto [Link],themarkupemittedcreatesaradiobuttonwhosename attributeissetto SuppliersGroup,whoseid attributeissettoRowSelectorX,whereX istheindexoftheGridViewrow,and whosevalue attributeissettotheindexoftheGridViewrow.
protectedvoidSuppliers_RowCreated(objectsender,GridViewRowEventArgse) { if([Link]==[Link]) { //GrabareferencetotheLiteralcontrol Literaloutput=(Literal)[Link]("RadioButtonMarkup")

14 of27

//Outputthemarkupexceptforthe"checked"attribute [Link]=[Link]( @"<inputtype=""radio""name=""SuppliersGroup"""+ @"id=""RowSelector{0}""value=""{0}""/>",[Link]) } }

WhenaGridViewrowisselectedandapostbackoccurs,weareinterestedintheSupplierID oftheselected [Link],onemightthinkthatthevalueofeachradiobuttonshouldbetheactualSupplierID (rather thantheindexoftheGridViewrow).Whilethismayworkincertaincircumstances,itwouldbeasecurityriskto [Link],forexample,listsonlythosesuppliersintheUSA. However,iftheSupplierID ispasseddirectlyfromtheradiobutton,whatstostopamischievoususerfrom manipulatingtheSupplierID valuesentbackonpostback?Byusingtherowindexasthevalue,andthengetting theSupplierID onpostbackfromtheDataKeys collection,wecanensurethattheuserisonlyusingoneofthe SupplierID valuesassociatedwithoneoftheGridViewrows. Afteraddingthiseventhandlercode,[Link],notethatonlyoneradio [Link],whenselectingaradiobuttonandclickingoneofthebuttons, apostbackoccursandtheradiobuttonsallreverttotheirinitialstate(thatis,onpostback,theselectedradiobutton isnolongerselected).Tofixthis,weneedtoaugmenttheRowCreated eventhandlersothatitinspectstheselected radiobuttonindexsentfromthepostbackandaddsthechecked="checked" attributetotheemittedmarkupofthe rowindexmatches. Whenapostbackoccurs,thebrowsersendsbackthename andvalue [Link] [Link]["name"].[Link] propertyprovidesa NameValueCollection [Link] fieldsinthewebpage,[Link] name attributeoftheradiobuttonsintheGridViewis SuppliersGroup,whenthewebpageispostedbackthe browserwillsendSuppliersGroup=valueOfSelectedRadioButton backtothewebserver(alongwiththeother formfields).[Link] propertyusing:[Link] ["SuppliersGroup"]. SincewellneedtodeterminetheselectedradiobuttonindexnotonlyintheRowCreated eventhandler,butinthe Click eventhandlersfortheButtonWebcontrols,letsaddaSuppliersSelectedIndex propertytothecode behindclassthatreturns1 ifnoradiobuttonwasselectedandtheselectedindexifoneoftheradiobuttonsis selected.
privateintSuppliersSelectedIndex { get { if([Link]([Link]["SuppliersGroup"])) return1 else returnConvert.ToInt32([Link]["SuppliersGroup"]) } }

Withthispropertyadded,weknowtoaddthechecked="checked" markupintheRowCreated eventhandlerwhen SuppliersSelectedIndex equals [Link]:


protectedvoidSuppliers_RowCreated(objectsender,GridViewRowEventArgse) {

15 of27

if([Link]==[Link]) { //GrabareferencetotheLiteralcontrol Literaloutput=(Literal)[Link]("RadioButtonMarkup") //Outputthemarkupexceptforthe"checked"attribute [Link]=[Link]( @"<inputtype=""radio""name=""SuppliersGroup"""+ @"id=""RowSelector{0}""value=""{0}""",[Link]) //Seeifweneedtoaddthe"checked"attribute if(SuppliersSelectedIndex==[Link]) [Link]+=@"checked=""checked""" //Addtheclosingtag [Link]+="/>" } }

Withthischange,[Link] specifywhatradiobuttonisselected,wecouldchangethebehaviorsothatwhenthepagewasfirstvisited,thefirst GridViewrowsradiobuttonwasselected(ratherthanhavingnoradiobuttonsselectedbydefault,whichisthe currentbehavior).Tohavethefirstradiobuttonselectedbydefault,simplychangetheif (SuppliersSelectedIndex==[Link]) statementtothefollowing:if(SuppliersSelectedIndex ==[Link]||(![Link]&&[Link]==0)). AtthispointwehaveaddedacolumnofgroupedradiobuttonstotheGridViewthatallowsforasingleGridView [Link] selectedsupplier.InStep4wellseehowtoredirecttheusertoanotherpage,sendingalongtheselected SupplierID.InStep5,wellseehowtodisplaytheselectedsuppliersproductsinaGridViewonthesamepage. Note:RatherthanusingaTemplateField(thefocusofthislengthyStep3),wecouldcreateacustom DataControlField [Link] DataControlField classisthebaseclassfromwhichtheBoundField,CheckBoxField,TemplateField,and [Link] classwould meanthatthecolumnofradiobuttonscouldbeaddedjustusingdeclarativesyntax,andwouldalsomake replicatingthefunctionalityonotherwebpagesandotherwebapplicationssignificantlyeasier. Ifyouveevercreatedcustom,[Link],however,youknowthatdoingsorequiresa fairamountoflegworkandcarrieswithitahostofsubtletiesandedgecasesthatmustbecarefullyhandled. Therefore,wewillforgoimplementingacolumnofradiobuttonsasacustomDataControlField classfor [Link],using,and deployingcustomDataControlField classesinafuturetutorial!

Step4:DisplayingtheSelectedSuppliersProductsinaSeparatePage
AftertheuserhasselectedaGridViewrow,[Link] circumstances,wemaywanttodisplaytheseproductsinaseparatepage,inotherswemightprefertodoitinthe samepage.LetsfirstexaminehowtodisplaytheproductsinaseparatepageinStep5welllookataddinga [Link] todisplaytheselectedsuppliersproducts. CurrentlytherearetwoButtonWebcontrolsonthepageListProducts [Link] SendToProducts Buttonisclicked,wewanttosendtheuserto ~/Filtering/[Link]/DetailFilteringAcross 16 of27

TwoPages tutorialanddisplaystheproductsforthesupplierwhoseSupplierID ispassedthroughthequerystring fieldnamedSupplierID. Toprovidethisfunctionality,createaneventhandlerfortheSendToProducts ButtonsClick event.InStep3we addedtheSuppliersSelectedIndex property,whichreturnstheindexoftherowwhoseradiobuttonisselected. ThecorrespondingSupplierID canberetrievedfromtheGridViewsDataKeys collectionandtheusercanthen besentto~/Filtering/[Link]?SupplierID=SupplierID using [Link]("url").
protectedvoidSendToProducts_Click(objectsender,EventArgse) { //Sendtheuserto~/Filtering/[Link] intsupplierID= Convert.ToInt32([Link][SuppliersSelectedIndex].Value) [Link]( "~/Filtering/[Link]?SupplierID=" +supplierID) } }

[Link],initially,the GridViewdoesnothaveanyradiobuttonsselected,andtheuserclickstheSendToProducts button, SuppliersSelectedIndex willbe1,whichwillcauseanexceptiontobethrownsince1 isoutoftheindex rangeoftheDataKeys [Link],however,ifyoudecidedtoupdatetheRowCreated event handlerasdiscussedinStep3soastohavethefirstradiobuttonintheGridViewinitiallyselected. ToaccommodateaSuppliersSelectedIndex valueof1,addaLabelWebcontroltothepageabovethe [Link] propertytoChooseSupplierMsg,itsCssClass propertytoWarning,itsEnableViewState andVisible propertiesto false,anditsText [Link] Warning displaystextinared,italic,bold,[Link] EnableViewState andVisible propertiesto false,theLabelisnotrenderedexceptforonlythosepostbacks wherethecontrolsVisible propertyisprogrammaticallysettotrue.

17 of27

Figure13:AddaLabelWebControlAbovetheGridView

Next,augmenttheClick eventhandlertodisplaytheChooseSupplierMsg LabelifSuppliersSelectedIndex is lessthanzero,andredirecttheuserto~/Filtering/[Link]? SupplierID=SupplierID otherwise.


protectedvoidSendToProducts_Click(objectsender,EventArgse) { //makesureoneoftheradiobuttonshasbeenselected if(SuppliersSelectedIndex<0) [Link]=true else { //Sendtheuserto~/Filtering/[Link] intsupplierID= Convert.ToInt32([Link][SuppliersSelectedIndex].Value) [Link]( "~/Filtering/[Link]?SupplierID=" +supplierID) } }

VisitthepageinabrowserandclicktheSendToProducts buttonbeforeselectingasupplierfromtheGridView. AsFigure14shows,thisdisplaystheChooseSupplierMsg [Link],selectasupplierandclickthe SendToProducts [Link]. [Link] pagewhentheBigfootBreweriessupplierwas selected.

18 of27

Figure14:TheChooseSupplierMsg LabelisDisplayedifNoSupplierisSelected

19 of27

Figure15:[Link]

Step5:DisplayingtheSelectedSuppliersProductsontheSamePage
InStep4wesawhowtosendtheusertoanotherwebpagetodisplaytheselectedsuppliersproducts. Alternatively,[Link],welladd [Link] todisplaytheselectedsuppliersproducts. SinceweonlywantthisGridViewofproductstodisplayonceasupplierhasbeenselected,addaPanelWeb controlbeneaththeSuppliers GridView,settingitsID toProductsBySupplierPanel anditsVisible property [Link],addthetextProductsfortheSelectedSupplier, followedbyaGridViewnamed [Link],choosetobindittoanewObjectDataSourcenamed ProductsBySupplierDataSource.

20 of27

Figure16:BindtheProductsBySupplier GridViewtoaNewObjectDataSource

Next,configuretheObjectDataSourcetousetheProductsBLL [Link] productsprovidedbytheselectedsupplier,specifythattheObjectDataSourceshouldinvokethe GetProductsBySupplierID(supplierID) [Link](None)fromthedropdownlists intheUPDATE,INSERT,andDELETEtabs.

21 of27

Figure17:ConfiguretheObjectDataSourcetoUsetheGetProductsBySupplierID(supplierID) Method

22 of27

Figure18:SettheDropDownListsto(None)intheUPDATE,INSERT,andDELETETabs

AfterconfiguringtheSELECT,UPDATE,INSERT,andDELETEtabs,[Link] GetProductsBySupplierID(supplierID) methodexpectsaninputparameter,theCreateDataSourcewizard promptsustospecifythesourcefortheparametersvalue. [Link] Parameterobject,andprogrammaticallyassignthevalueoftheSuppliersSelectedIndex propertytothe ParametersDefaultValue propertyintheObjectDataSourcesSelecting [Link] ProgrammaticallySettingtheObjectDataSource'sParameterValuestutorialforarefresheronprogrammatically assigningvaluestotheObjectDataSourcesparameters. Alternatively,wecanuseaControlParameterandrefertotheSuppliers GridViewsSelectedValue property (seeFigure19).TheGridViewsSelectedValue propertyreturnstheDataKey valuecorrespondingtothe SelectedIndex [Link],weneedtoprogrammaticallysettheGridViews SelectedIndex propertytotheselectedrowwhentheListProducts [Link],by settingtheSelectedIndex,theselectedrecordwilltakeontheSelectedRowStyle definedinthe DataWebControls Theme(ayellowbackground).

23 of27

Figure19:UseaControlParametertoSpecifytheGridViewsSelectedValueastheParameterSource

Uponcompletingthewizard,[Link] buttheProductName,CategoryName,andUnitPrice BoundFields,andchangetheHeaderText propertiesto Product, Category, andPrice. ConfiguretheUnitPrice BoundFieldsothatitsvalueisformattedasa [Link],thePanel,GridView,andObjectDataSourcesdeclarativemarkupshould looklikethefollowing:
<asp:Panelrunat="server"ID="ProductsBySupplierPanel"Visible="False"> <h3> ProductsfortheSelectedSupplier</h3> <p> <asp:GridViewID="ProductsBySupplier"runat="server" AutoGenerateColumns="False"DataKeyNames="ProductID" DataSourceID="ProductsBySupplierDataSource"EnableViewState="False"> <Columns> <asp:BoundFieldDataField="ProductName"HeaderText="Product" SortExpression="ProductName"/> <asp:BoundFieldDataField="CategoryName"HeaderText="Category" ReadOnly="True"SortExpression="CategoryName"/> <asp:BoundFieldDataField="UnitPrice"DataFormatString="{0:c}" HeaderText="Price"HtmlEncode="False" SortExpression="UnitPrice"/> </Columns> </asp:GridView> <asp:ObjectDataSourceID="ProductsBySupplierDataSource"runat="server"

24 of27

OldValuesParameterFormatString="original_{0}" SelectMethod="GetProductsBySupplierID"TypeName="ProductsBLL"> <SelectParameters> <asp:ControlParameterControlID="Suppliers"Name="supplierID" PropertyName="SelectedValue"Type="Int32"/> </SelectParameters> </asp:ObjectDataSource> </p> </asp:Panel>

Tocompletethisexercise,weneedtosettheGridViewsSelectedIndex propertytothe SelectedSuppliersIndex andtheProductsBySupplierPanel PanelsVisible propertytotrue whenthe ListProducts [Link],createaneventhandlerfortheListProducts ButtonWeb controlsClick eventandaddthefollowingcode:
protectedvoidListProducts_Click(objectsender,EventArgse) { //makesureoneoftheradiobuttonshasbeenselected if(SuppliersSelectedIndex<0) { [Link]=true [Link]=false } else { //SettheGridView'sSelectedIndex [Link]=SuppliersSelectedIndex //ShowtheProductsBySupplierPanelpanel [Link]=true } }

IfasupplierhasnotbeenselectedfromtheGridView,theChooseSupplierMsg Labelisdisplayedandthe ProductsBySupplierPanel [Link],ifasupplierhasbeenselected,the ProductsBySupplierPanel isdisplayedandtheGridViewsSelectedIndex propertyisupdated. Figure20showstheresultsaftertheBigfootBreweriessupplierhasbeenselectedandthe ShowProductson Pagebuttonhasbeenclicked.

25 of27

Figure20:TheProductsSuppliedbyBigfootBreweriesareListedontheSamePage

Summary
AsdiscussedintheMaster/DetailUsingaSelectableMasterGridViewwithaDetailsDetailViewtutorial,records canbeselectedfromaGridViewusingaCommandFieldwhoseShowSelectButton [Link] theCommandFielddisplaysitsbuttonseitherasregularpushbuttons,links,[Link] [Link] examinedhowtoaddacolumnofradiobuttons. Unfortunately,[Link] builtinRadioButtonFieldthatcanbeaddedattheclickofabutton,andusingtheRadioButtonWebcontrolwithin [Link],toprovidesuchaninterfaceweeitherhaveto createacustomDataControlField classorresorttoinjectingtheappropriateHTMLintoaTemplateFieldduring theRowCreated event. Havingexploredhowtoaddacolumnofradiobuttons,letusturnourattentiontoaddingacolumnofcheckboxes. 26 of27

Withacolumnofcheckboxes,ausercanselectoneormoreGridViewrowsandthenperformsomeoperationon alloftheselectedrows(suchasselectingasetofemailsfromawebbasedemailclient,andthenchoosingto deleteallselectedemails).Inthenexttutorialwellseehowtoaddsuchacolumn. HappyProgramming!

AbouttheAuthor
ScottMitchell,authorofsevenASP/[Link],hasbeenworkingwith [Link],trainer,[Link] [Link]@[Link]. or viahisblog,whichcanbefoundat [Link]

SpecialThanksTo
[Link]. InterestedinreviewingmyupcomingMSDNarticles?Ifso,dropmealineat mitchell@[Link].

27 of27

You might also like