Use the datalist control to present and edit data ...

xiaoxiao2021-03-06  67

By: John Kilgo Date: January 23, 2003 Download The Code.

Printer Friendly Version

The DataList is not as powerful as the DataGrid. It requires more work from you since it has no default data presentation format. However, the DataGrid begins to get very cumbersome as the number of columns of data you present increases. Anything more than half a dozen columns or so and you probably induce horizontal scrolling -. a real no-no for me If you put such a DataGrid into edit mode then you really have a horizontal scrolling problem The DataList, with its ItemTemplate and EditItemTemplate, make it very easy. for you to control the appearance (and screen real estate) of the data. As I said before, it requires more coding but the results may well be worth the effort. In this article and example program we will deal with the Northwind Customers table. I have included nine columns of editable data. I have divided the work between an aspx page and a code-behind page. in the aspx page we layout our presentation of data, while the code-behind file places the DataList in edit mode, a nd handles the updating of modified data. The aspx file will be shown below in several sections to make it easier to explain what each section does. This first section is the usual top-of-page "stuff" and the definition of the DataList Control ....................................

<% @ Page language = "vb" src = "DATALISTEDIT.ASPX.VB" inherits = "main"%> DataList Edit </ title> <style rel = "stylesheet"> .customers {Font: 9pt Verdana, Arial, Sans-Serif;} .customershead {font: bold 8pt Verdana, Arial, Sans-Serif; Background-Color: # 4A3C8C; Color: White;} a {text-decoration: underline;} a : Hover {text-decoration: underline; color: # 4a3c8c;} </ style> </ head> <body> <form runat = "server" id = "form1"> <div align = "center"> <h3> Customers Table </ h3> </ div> <asp: DataList id = "dtlcustomers" runat = "server" width = "760" BorderWidth = "1" HeaderStyle-CssClass = "customersHead" AlternatingItemStyle-BackColor = "# DEDFDE" Font -Size = "10" align = "center" OneDitCommand = "dtlcustomers_edit" onupdateCommand = "dtlcustomers_update" oncancelcommand = "dtlcustomers_cancel"></p> <p>The following section includes the ItemTemplate for presentation of our data. The code (markup) is fairly long, but all we are doing is creating an html table to present the data. The CompanyName column is shown in a TD element of its own. The rest of the data and column descriptions are show two columns abreast. Notice that we are specifically naming the column headings in one TD element and using the Eval method of the DataBinder class to obtain the actual database table data. We are also using a Button control to induce edit mode in the code-behind file. you can use a LinkButton if you prefer a textual presentation. This may look a little messy at first, but if you run the program (from the link at the bottom of the article) and Compare the output to what you see belove you find it very straight forward.</p> <p><Itemtemplate> <Table cellpadding = "2" cellspacing = "0" width = "100%"> <Tr> <TD colspan = "4" class = "customershead"> <h3> <% # databinder.eval (container. DataITEM, "CompanyName")> </ h3> <td width = "100%" align = "left" colSpan = "4"> <ask: button id = "btnedit" Runat = "server" CommandName = "edit" text = "edit" /> </ td> </ tr> <tr> <td width = "25%" align = "left"> <b> Contact Name </ b > </ Td> <td width = "25%" align = "left"> <% # databinder.eval (container.DataItem, "contactName")%> </ td> <td width = "25%" align = "Left"> <b> Contact Title </ b> </ td> <td width = "25%" align = "left"> <% # databinder.eval (container.DataItem, "ContactTitle")%> </ TD> </ tr> <tr> <td width = "25%" align = "left"> <b> address </ b> </ td> <td width = "25%" align = "left"> < % # DataBinder.eval (Container.DataItem, "Address")%> </ td> <td width = "25%" align = "left"> <b> city </ b> </ td> <td width = "25%" align = "left"></p> <p><% # DataBinder.eval (Container.DataItem, "City")%> </ td> </ tr> <tr> <td width = "25%" align = "left"> <b> Postal code </ b > </ Td> <td width = "25%" align = "left"> <% # databinder.eval (container.DataItem, "postalcode")%> </ td> <TD width = "25%" align = "Left"> <b> country </ b> </ td> <td width = "25%" align = "left"> <% # databinder.eval (container.DataItem, "country")%> </ td > </ Tr> <tr> <td width = "25%" align = "left"> <b> phone </ b> </ td> <td width = "25%" align = "left"> <% # DataBinder.eval (Container.DataItem, "Phone")% >> </ td> <td width = "25%" align = "left"> <b> fax </ b> </ td> <td width = "25%" align = "left"> <% # databinder.eval (container.dataitem, "fax")%> </ td> </ tr> </ table> </ itemtemplate></p> <p>Next we must decide how our data and column descriptions are to appear while in edit mode. That is the purpose of the markup below following the EditItemTemplate tag. The process is much the same as in the ItemTemplate section above. The main difference is that we are creating TextBox controls to contain the actual data, so that the data becomes editable. I also chose to present the column descriptions and data one abreast rather than two abreast as above. I did this for two reasons. One was just to show that the ItemTemplate and EditItemTemplates stand alone and do not have to have the same presentation format, and to make more room for several of the TextBoxes that can hold 30 -. 40 characters of data Again, once you run the program you will see the difference in presentation .</p> <p><Edititemtemplate> <Table cellpadding = "2" cellspacing = "0" width = "100%"> <tr> <TD colspan = "2" class = "customershead"> <h3> <% # databinder.eval (container. DataITEM, "CompanyName")%> </ h3> </ td width = "50%" align = "left"> <b> Company name </ b> </ td> <td width = "50%" align = "left"> <ask: textbox id = "txtcompanyname" runat = "server" maxlength = "40" columns = "40" text = '<% # databinder.eval (container. DataItem, "CompanyName")%> '/> </ td> </ tr> <tr> <td width = "50%" align = "left"> <b> Contact Name </ b> </ td> < Td width = "50%" align = "left"> <ask: textbox id = "txtContactName" runat = "server" maxlength = "30" columns = "30" text = '<% # databinder.eval (container.dataitem , "ContactName")%> '/> <td width = "50%" align = "left"> <b> Contact Title </ b> </ td> <TD Width = "50%" align = "left"> <ask: textbo X id = "txtContactTitle" runat = "server" maxlength = "30" columns = "30" text = '<% # databinder.eval (container.dataitem, "</p> <p>ContactTitle ")%> '/> </ td width =" 50% "align =" left "> <b> address </ b> </ td> <td width =" 50% "align =" left "> <ask: textbox id =" txtaddress "runat =" server "maxlength =" 60 "columns =" ​​60 "text = '<% # databinder.eval (container.DataItem," address " )%> '/> </ Td width = "50%" align = "left"> <b> city </ b> </ td> <td width = "50% "Align =" left "> <ask: textbox id =" txtcity "runat =" server "maxlength =" 15 "columns =" ​​15 "text = '<% # databinder.eval (container.DataItem," city ")% > '/> </ Td> </ TD Width = "50%" align = "left"> <b> postal code </ b> </ td> <td width = "50%" Align = "left"> <ask: textbox id = "txtpostalcode" runat = "server" maxlength = "10" columns = "10" text = '<% # databinder.eval (container.DataItem, "postalcode")%> '/> </ Td> </ tr> <tr> <td width = "50%" align = "left"> <b> c Ountry </ b> </ td> <td width = "50%" align = "left"> <ask: textbox id = "txtcountry"</p> <p>Runat = "server" maxlength = "15" columns = "15" text = '<% # databinder.eval (container.dataitem, "country")%>' /> </ td> </ tr> <tr> < Td width = "50%" align = "left"> <b> phone </ b> </ td> <td width = "50%" align = "left"> <ask: textbox id = "txtphone" runat = "server" maxlength = "24" columns = "24" text = '<% # databinder.eval (container.dataitem, "phone")%>' /> </ td> </ tr> <tr> <TD Width = "50%" align = "left"> <b> fax </ b> </ td> <TD width = "50%" align = "left"> <ask: textbox id = "txtfax" runat = "server "MaxLength =" 24 "columns =" ​​24 "text = '<% # databinder.eval (container.dataitem," fax ")%>' /> </ td> </ tr> <TR> <TD colSpan =" 2 "> <ask: label id =" lblcustomerid "runat =" server "text = '<% # databinder.eval (" CustomerID ")%>' visible =" false "/> </ td> < / TR> <TR> <TD width = "50%" align = "right"> <ask: Button I D = "btnupdate" runat = "server" commandname = "update" text = "update" /> <ask: button id = "btncecance"</p> <p>Runat = "server" CommandName = "cancel" text = "cancel" /> </ td> <td width = "50%" align = "left"> </ td> </ tr> </ table> </ edititemtemplate > </ asp: datalist> </ form> </ body> </ html> now for the code-behind file. We will also present this file in sections to better illustrate and explain the code. first Are the page_load and bindtate ( ) subroutines. The Page_Load simply checks to make sure this is the first time the page has been loaded and calls the BindTheData subroutine. BindTheData uses a DataAdapter to obtain the data from the table, fills a DataSet and binds the data to the DataList control ( DTLCUSTOMERS).</p> <p>Imports SystemImports System.DataImports System.Data.SqlClientImports System.Web.UIImports System.Web.UI.WebControlsImports System.ConfigurationPublic Class Main: Inherits Page Private strConn As String = ConfigurationSettings.AppSettings ( "ConnectionString") Public dtlCustomers As DataList Public Sub Page_Load (sender as Object, e as EventArgs) If Not IsPostBack Then BindTheData () End If End Sub Private Sub BindTheData () Dim objConn as new SqlConnection (strConn) Dim strSQL as String strSQL = "SELECT Top 5 * FROM Customers" Dim sda as New SqlDataAdapter (STRSQL, Objconn) DIM DS AS NEW DATASET () SDA.FILL (DS, "Customers") DTLCUSTOMERS.DATASOURCE = DS.TABLES ("Customers"). DefaultView DTLCustomers.DATABIND () End Sub</p> <p>Next are two short bits of code to handle the dtlCustomers_Edit and dtlCustomers_Cancel subroutines. Remember in the aspx file above we set several properties of the Datalist control to call events in the code-behind file. Edit and Cancel were two of those. We set the OnEditCommand property equal to "dtlcustomers_Edit". We also created a button with a CommandName of "edit". The combination of the two brings us to the edit subroutine presented below. We use the ItemIndex property to know which row is to be edited. We also created a Cancel button (and set the OnCancelCommand property) to get us out of edit mode if we want to abandon changes rather than going ahead with the update of the row. Cancel is handled easily simply by setting the EditItemIndex property to -1. public Sub dtlCustomers_Edit (sender as Object, e as DataListCommandEventArgs) dtlCustomers.EditItemIndex = e.Item.ItemIndex BindTheData () End Sub public Sub dtlCustomers_Cancel (sender as Object, e as DataListCommandEv DTLCUSTOMERS.EDITITEMINDEX = -1 bindthedata () End Sub</p> <p>The last section of code presented is the dtlCustomers_Update subroutine and is by far the longest section. As you may recall in the aspx page EditItemTemplate we created TextBoxes to present data for editing. The value in those TextBox controls are used to change the data. The values ​​of the textboxes are gathered and placed in string variables in the code immediately below using the FindControl method. We now have the data after any editing that took place. Immediately below that is our update statement which is constructed using parameters for the column values. BELOW THAT WE Add Parameters to the Sqlcommand Object and Set The Parameter Values ​​To The String Variables Holding Our Edited Data. Following That We Simply Do The Update and The Rebind The DataList Control.</p> <p>Public Sub dtlCustomers_Update (sender As Object, e As DataListCommandEventArgs) Dim strCompanyName, strContactName, strContactTitle, strCustomerID As String Dim strAddress, strCity, strPostalCode, strCountry, strPhone, strFax As String strCompanyName = CType (e.Item.FindControl ( "txtCompanyName") , TextBox) .Text strContactName = CType (e.Item.FindControl ( "txtContactName"), TextBox) .Text strContactTitle = CType (e.Item.FindControl ( "txtContactTitle"), TextBox) .Text strAddress = CType (e.Item .FindControl ( "txtAddress"), TextBox) .Text strCity = CType (e.Item.FindControl ( "txtCity"), TextBox) .Text strPostalCode = CType (e.Item.FindControl ( "txtPostalCode"), TextBox) .Text strCountry = CType (e.Item.FindControl ( "txtCountry"), TextBox) .Text strPhone = CType (e.Item.FindControl ( "txtPhone"), TextBox) .Text strFax = CType (e.Item.FindControl ( "txtFax "), TextBox) .Text strcustomerid = ctype (E.Item.FindControl (" lblcustomerid "), label) .Text Dim Strsql as string strsql =" Update Customers "_ &" set companyname = @companyname, "_ &" contactname = @contactname, "_" "" _ " "Postalcode = @postalcode," _ "," _ "" @PHONE, "_ &" fax = @fax "_ &" where customerid = @customerid "</p> <p>Dim objConn As New SqlConnection (strConn) Dim cmdSQL As New SqlCommand (strSQL, objConn) cmdSQL.Parameters.Add (new SqlParameter ( "@ CompanyName", SqlDbType.NVarChar, 40)) cmdSQL.Parameters ( "@ CompanyName"). Value = strCompanyName cmdSQL.Parameters.Add (new SqlParameter ( "@ ContactName", SqlDbType.NVarChar, 30)) cmdSQL.Parameters ( "@ ContactName"). Value = strContactName cmdSQL.Parameters.Add (new SqlParameter ( "@ ContactTitle", SqlDbType.NVarChar, 30)) cmdSQL.Parameters ( "@ ContactTitle"). Value = strContactTitle cmdSQL.Parameters.Add (new SqlParameter ( "@ Address", SqlDbType.NVarChar, 60)) cmdSQL.Parameters ( "@ Address") .Value = strAddress cmdSQL.Parameters.Add (new SqlParameter ( "@ City", SqlDbType.NVarChar, 15)) cmdSQL.Parameters ( "@ City"). Value = strCity cmdSQL.Parameters.Add (new SqlParameter ( "@ PostalCode "Sqldbtype.nvarchar, 10)))) cmdsql.Parameters (" @ posthalcode "). Value = strpostalcode cmdsql.parameters.add (New Sqlparameter (" @ country ", sqldbtype.nvarchar, 15)) cm dSQL.Parameters ( "@ Country"). Value = strCountry cmdSQL.Parameters.Add (new SqlParameter ( "@ Phone", SqlDbType.NVarChar, 24)) cmdSQL.Parameters ( "@ Phone"). Value = strPhone cmdSQL.Parameters .Add ("@ fax", sqldbtype.nvarchar, 24)) cmdsql.Parameters ("@ fax"). Value = strfax cmdsql.parameters.add (New Sqlparameter ("@ Customerid", SqldbType.Nchar, 5 )) Cmdsql.parameters ("@ Customerid"). Value =</p> <p>strCustomerID objConn.Open () cmdSQL.ExecuteNonQuery () objConn.Close () dtlCustomers.EditItemIndex = -1 BindTheData () End SubEnd ClassConclusion: You have seen a lot coding necessary to presenting a DataList, placing it in edit mode, and then canceling or updating the data after making changes. If you take the code one section at a time and see what each section actually does, I believe you will find that you can finely tune how your data is presented both for viewing and for editing, and how TO Accomplish the Update. Best of luck! you may down the code here.you may download the code.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110019.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="110019" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.043</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'Saub1Nnj41HFNxcGCzixa3b34UYiVyr3khSR0zyFS0AIwNjbLZJ3F3vRRNUX9Jgf0OjBoa1kww_2FKx8DA'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>