ASP.NET 2.0 Data Control Tips and Tricks - PDF

Please download to get full document.

View again

of 34
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Information Report
Category:

Court Filings

Published:

Views: 16 | Pages: 34

Extension: PDF | Download: 0

Share
Related documents
Description
ASP.NET 2.0 Data Control Tips and Tricks Paul Litwin Collaborative Data Services (CDS) Fred Hutchinson Cancer Research Center CDS Brownbag Series This is the restart of the popular CDS
Transcript
ASP.NET 2.0 Data Control Tips and Tricks Paul Litwin Collaborative Data Services (CDS) Fred Hutchinson Cancer Research Center CDS Brownbag Series This is the restart of the popular CDS brownbag series Materials for the series can be downloaded from cds.fhcrc.org Sign up to be on our list at cds.fhcrc.org CDS Collaborative Data Services Providing data services through FHCRC (and beyond) Our services include Telephone interviewing of subjects Data entry & scanning Programming Web and database hosting More info at Slides & Samples Download You can download them from: cds.fhcrc.org Agenda ASP 2.0 Data Binding Overview Programming GridView Programming DetailsView and FormView Data Control How To s ASP 2.0 Data Binding Two Types Of Data-related Controls Data-bound Controls UI controls that render data GridView, DetailsView, FormView, TreeView, Menu Can auto-bind to data exposed from a data source control (via DataSourceID) Will fetch data at the appropriate time in lifecycle Can optionally take advantage of data source capabilities Can also work directly with Datasets (via DataSource) Data Source Controls Non-UI controls that serve as middleman/woman between data-bound controls and data source SQLDataSource, AccessDataSource, ObjectDataSource, XmlDataSource, SiteMapDataSource Represent different backend data sources SQL Databases, Access, Business Objects, XML/Web Services, SiteMap Can easily extend by writing custom data sources Provide rich capabilities over data Sorting, paging, filtering, updating, deleting, inserting Expose data through tabular or hierarchical interfaces to data-bound controls Programming GridView GridView asp:gridview ID= gvCustomers runat= server DataSourceID= sdsCustomers DataKeyNames= CustomerID Columns asp:commandfield ShowDeleteButton= True ShowEditButton= True / asp:boundfield DataField= CustomerID HeaderText= CustomerID ReadOnly= True SortExpression= CustomerID / asp:boundfield DataField= City HeaderText= City SortExpression= City / /Columns /asp:gridview asp:sqldatasource ID= sdsCustomers runat= server ConnectionString= %$ ConnectionStrings:cnxNwind % SelectCommand= SELECT [CustomerID], [CompanyName], [ContactName], [City], [Country] FROM [Customers] DeleteCommand= DELETE FROM [Customers] WHERE [CustomerID] DeleteParameters asp:parameter Name= original_CustomerID Type= String / /DeleteParameters /asp:sqldatasource Programming GridView: Things You Need to Know 1. How to hook in What events are most useful When to use events of GridView vs. Data Source Control 2. How to programmatically access controls and fields GridView Events of Note DataBound Use to modify data as it is being loaded into control, e.g., setting a default value RowUpdating Use to manipulate data before row is updated in database, e.g., saving a timestamp field. RowDeleting Use to manipulate data before row is deleted from database, e.g., stopping delete. RowUpdated Use to react to database update, e.g. refreshing another control on page or handling update exceptions. RowDeleted Use to react to database delete, e.g. refreshing another control on page or handling delete exceptions Programming DetailsView and FormView The Single-Record Form Problem ASP.NET 1.x provided no help to the developer having to create a single-record form view of data ASP.NET 2.0 gives us two solutions DetailsView places fields in a table uses BoundFields by default (with no ID property) FormView uses a free-form template uses template fields by default more flexibility Both support editing, inserts, pagination, template fields, validation controls DetailsView asp:detailsview ID= dvCustomers runat= server ... DataKeyNames= CustomerID DataSourceID= sdsCustomers Fields asp:boundfield DataField= CustomerID HeaderText= CustomerID ReadOnly= True SortExpression= CustomerID / asp:boundfield DataField= CompanyName HeaderText= CompanyName SortExpression= CompanyName / asp:commandfield ShowDeleteButton= True ShowEditButton= True ShowInsertButton= True / /Fields /asp:detailsview asp:sqldatasource ID= sdsCustomers runat= server ConnectionString= %$ ConnectionStrings:cnxNwind % SelectCommand= SELECT [CustomerID], [CompanyName],... FROM [Customers] ORDER BY [CompanyName] DeleteCommand= DELETE FROM [Customers] WHERE [CustomerID] InsertCommand= INSERT INTO [Customers] ([CustomerID],...) VALUES UpdateCommand= UPDATE [Customers] SET [CompanyName] WHERE [CustomerID] UpdateParameters asp:parameter Name= CompanyName Type= String / asp:parameter Name= ContactName Type= String / asp:parameter Name= ContactTitle Type= String / /UpdateParameters /asp:sqldatasource FormView asp:formview ID= fvcustomers runat= server ... DataKeyNames= CustomerID DataSourceID= sdsCustomers ItemTemplate strong span style= color: white; background-color: #9471DE CustomerID: asp:label ID= CustomerIDLabel runat= server Text=' %# Eval( CustomerID ) % ' /asp:label /span /strong br / CompanyName: asp:label ID= CompanyNameLabel runat= server Text=' %# Bind( CompanyName ) % ' /asp:label br / /ItemTemplate EditItemTemplate CustomerID: asp:label ID= CustomerIDLabel1 runat= server Text=' %# Eval( CustomerID ) % ' /asp:label br / CompanyName: asp:textbox ID= CompanyNameTextBox runat= server Text=' %# Bind( CompanyName ) % ' /asp:textbox asp:requiredfieldvalidator ID= rfvCompanyName ControlToValidate= CompanyNameTextBox runat= server ErrorMessage= Company Name is required. /asp:requiredfieldvalidator br / /asp:formview Programming DetailsView and FormView: Things You Need to Know 1. How to hook in What events are most useful When to use events of Data Control vs. Data Source Control 2. How to programmatically access controls and fields Details/Form View Events of Note (1 of 2) DataBound and the ing Events DataBound Use to modify data as it is being loaded into control, e.g., setting a default value ItemUpdating Use to manipulate data before row is updated in database, e.g., saving a timestamp field. ItemInserting Use to manipulate data before row is inserted to database, e.g., saving a timestamp field. ItemDeleting Use to manipulate data before row is deleted from database, e.g., stopping delete. Details/Form View Events of Note (2 of 2) The ed Events ItemUpdated Use to react to database update, e.g. refreshing another control on page or handling update exceptions. ItemInserted Use to react to database insert, e.g. refreshing another control on page or handling insert exceptions ItemDeleted Use to react to database delete, e.g. refreshing another control on page or handling delete exceptions DataSourceControl Inserted Useful for grabbing Identity field value and refreshing page to display new record Note: this is an event of the DataSource control, not the Data control! Data Control How To s How do I 1. Filter one data control based on another? 2. Set a default value of a control for an insert? 3. Confirm a record delete for a data control? 4. Use a drop-down control for editing with a data control? 5. Update fields that aren t shown (e.g., time stamp fields) when a row is updated? 6. Refresh one control when another changes? 7. Not pass an identity column during an insert to the database? and After the insert, retrieve the newly inserted record, complete with identity column? 8. Handle exceptions? 1. How do I Filter one data control based on another? Create a ControlParameter in the second control s Data Source control that points to the selected value of the first control Example:GridViewFiltered.aspx asp:sqldatasource SelectParameters asp:controlparameter ControlID= ddlCountryFilter Name= Country PropertyName= SelectedValue Type= String / /SelectParameters /asp:sqldatasource Different Types of Parameters You re not limited to using Control Parameters Also available asp:querystringparameter asp:cookieparameter asp:profileparameter asp:sessionparameter asp:parameter 2. How do I Set a default value of a control for an insert? Use DataBound event, checking the CurrentMode property protected void fvcustomers_databound(object sender, EventArgs e) { if (fvcustomers.currentmode == FormViewMode.Insert) { ((TextBox)fvCustomers.FindControl( CityTextBox )).Text = Seattle ; ((TextBox)fvCustomers.FindControl( CountryTextBox )).Text = USA ; } } Example: FormView.aspx 2a. How do I What about finding control when using DetailsView? Problem: you can t get at controls by name unless you use template field. Solution: use template field asp:templatefield HeaderText= Country ItemTemplate asp:label runat= server ID= lblCountry Text=' %#Bind( Country )% ' / /ItemTemplate EditItemTemplate asp:textbox runat= server ID= txtCountryEdit Text=' %#Bind( Country )% ' / /EditItemTemplate InsertItemTemplate asp:textbox runat= server ID= txtCountryInsert Text=' %#Bind( Country )% ' / /InsertItemTemplate /asp:templatefield Example: DetailsViewDefault.aspx 3. How do I Confirm a record delete for a data control? Use a templated LinkButton control w/ client-side JavaScript asp:templatefield ItemTemplate asp:linkbutton ID= lbDelete Runat= server OnClientClick= return confirm('ok to delete record?'); CommandName= Delete Text = Delete /asp:LinkButton /ItemTemplate /asp:templatefield Example: GridViewUpdate2DeleteConfirm.aspx 4. How do I Use a drop-down control for editing with a data control? Use a template field asp:templatefield HeaderText= ReportsTo SortExpression= ReportsTo EditItemTemplate asp:dropdownlist ID= ddlReportsTo runat= server SelectedValue=' %# Bind( ReportsTo ) % ' DataSourceID= sdsReportsTo DataTextField= EmployeeName DataValueField= EmployeeId /asp:DropDownList /EditItemTemplate ItemTemplate asp:label ID= lblReportsTo runat= server Text=' %# Bind( ReportsToName ) % ' /asp:label /ItemTemplate /asp:templatefield Example: EmployeeGridWithDropDown.aspx 4. How do I Use a drop-down control for editing with a data control? (continued) Don t forget to provide a NULL to the list! asp:sqldatasource ID= sdsReportsTo runat= server ... SelectCommand= SELECT EmployeeId, LastName + ', ' + FirstName AS EmployeeName FROM Employees UNION SELECT NULL, NULL ORDER BY LastName + ', ' + FirstName /asp:sqldatasource 5. How do I Update fields that aren t shown (e.g., time stamp fields) when a row is updated? Template the fields so you can control updatability/visibility during edits/inserts For Insert Use ItemInserting event and Values collection For Update Use ItemUpdating event and NewValues collection Example: DetailsViewHiddenFields.aspx 6. How do I Refresh one control when another changes? Call DataBind() method of second control from first control s ed event Example: DrillDown1Page.aspx 7. How do I Not pass an identity column during an insert to the database? Set InsertVisible property of control to false After the insert, retrieve the newly inserted record, complete with identity column? Uses Inserted event of DataSource control and grab the value of the identity column using e.command.parameters collection Example: EmpDrillDown.aspx/EmpDetails.aspx 8. How do I Handle Exceptions? Use one of ed events & retrieve exception: Exception exp = e.exception; if (exp!= null) { lblmsg.text = Insert failed. Details: + exp.message; // If using ObjectDataSource use exp.innerexception.message instead e.exceptionhandled = true; e.keepininsertmode = true; // keeps user editing. } Example: FormViewExp.aspx Gotchas to Watch Out For Gotcha: Problem updating your control? Check for correct DataKeyNames property of data control Gotcha: When hooking up stored procedures to DataSource controls containing output parameters, Visual Studio will set the Direction to inputoutput instead of output which will create problems Fix: Change direction to output Gotcha: If a page hides and unhides DetailsView/FormView controls, it may produce a bogus Failed to load viewstate error message Fix: Set EnableViewState property to False for each of the DetailsView/FormView controls Questions? Thank You! Contact: Download slides & samples from cds.fhcrc.org
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks
SAVE OUR EARTH

We need your sign to support Project to invent "SMART AND CONTROLLABLE REFLECTIVE BALLOONS" to cover the Sun and Save Our Earth.

More details...

Sign Now!

We are very appreciated for your Prompt Action!

x