"ASP." Data binding-datalist Practice Chapter

Source: Internet
Author: User
The previous article about some of the basic knowledge of DataList, mastering these knowledge in the future application plays a big role, and now we begin to talk about the basic knowledge of the previous article to do a small example.

First of all, I have a person table in my database, as shown in.


Now, we use the DataList control to display the information in the table and to edit the tables in the database on the DataList control.

1. First create a Web application with VS, add a Web form, pull in the DataList control in the web window, right-click the control, select Edit Item template, here we can see four templates, Two of them are selecteditemtemplate and EditItemTemplate, pulling two LinkButton controls in the ItemTemplate template, one renaming text to view, and the CommandName property to select , the other one changes the text to edit, and its CommandName property is changed to edit. Then create the SelectedItemTemplate template on the HTML page, and bind all of the employee's information in the template. (This is a feature that enables you to view employee details.)

2. Add two LinkButton controls in the EditItemTemplate template item, the Text property is save and cancel respectively, the CommandName property is update and cancel respectively, and then add a TextBox control to enter the name, The ability to modify employee names is implemented here.

3, we can also always change the style of the table in the Property builder, the color of the font, the distance of the grid to change a bit, here in detail no longer allocations, and finally end the template editing.

4. Edit foreground HTML code

Code in the ItemTemplate template (used to display the employee's name)

                <ItemTemplate>                    <asp:linkbutton id= "lbtnshowdetails" runat= "Server" commandname= "select" Forecolor= " Red > View </asp:LinkButton>                    <asp:linkbutton id= "Lbtnedit" runat= "Server" commandname= "edit" ForeColor = "Red" > Edit </asp:LinkButton>                    <%# DataBinder.Eval (Container.DataItem, "PersonName")%>                </ Itemtemplate>


Code in the SelectedItemTemplate template (used to display details in an employee)

                 <SelectedItemTemplate>                    Employee ID: <%# DataBinder.Eval (Container.DataItem, "PID")%>                    <br/>                    Employee Name: <%# DataBinder.Eval (Container.DataItem, "PersonName")%>                    <br/>                    staff sex: <%# DataBinder.Eval (Container.DataItem, "Personsex")%>                </SelectedItemTemplate>


Code in the EditItemTemplate template (used to modify employee names) Note: Bind the Text property in the textbox to the employee's name.


                <EditItemTemplate>                    <asp:linkbutton id= "lbtnupdate" runat= "Server" commandname= "Update" > Save </asp :linkbutton>                    <asp:linkbutton id= "Lbtncancel" runat= "Server" commandname= "Cancel" > Cancel </asp: linkbutton> <br/>                    Employee Number: <%# DataBinder.Eval (Container.DataItem, "PID")%> <br                    /> name:< Asp:textbox id= "txtname" runat= "Server"                     <span style= "color: #FF0000;" >text= ' <%# DataBinder.Eval (Container.DataItem, "PersonName")%> ' </span> width= "50px" >                    </ Asp:textbox>                </EditItemTemplate>



Finally, the header and footer templates

              <HeaderTemplate>                    header of the template                </HeaderTemplate>               <FooterTemplate>                    <br/>                    Footer for templates                </FooterTemplate>


5, the editing of the front desk interface is as follows




6, the background code writing

6.1, the method of writing DataList data binding

private void Databindtodatalist ()        {            SqlConnection con = db.createconnection ();            SqlDataAdapter SDA = new SqlDataAdapter ();            String sql = "SELECT * from person";            Sda. SelectCommand = new SqlCommand (sql, con);            DataSet ds = new DataSet ();            Sda. Fill (ds, "per");            Datalist1.datakeyfield = "PID";  The primary key is stored in the DataKeys collection so that a piece of data can be edited later.            Datalist1.datasource = ds. Tables["per"];            Datalist1.databind ();        }

6.2, write the Page_loda event, determine whether the page is loaded for the first time, and bind the data when the page is loaded for the first time.

   protected void Page_Load (object sender, EventArgs e)        {            if (!this. IsPostBack)            {                this.databindtodatalist ();            }        }

6.3. Write the Datalist1_itemcommand event to see the Employee Details feature (provided that we have already bound the details of the employee in the SelectedItemTemplate template, and now just call the method to display it)

protected void Datalist1_itemcommand (object source, DataListCommandEventArgs e)//E represents the information that DataList passes to the function.        {            if (e.commandname = = "Select")            {this                . Datalist1.selectedindex = E.item.itemindex;                This.databindtodatalist ();            }        }



6.4, write the Datalist1_editcommand event, realize the editing function, will display the information in the EditItemTemplate template.

protected void Datalist1_editcommand (object source, DataListCommandEventArgs e)//E represents the information that DataList passes to the function.        {this            . Datalist1.edititemindex = E.item.itemindex;//e.item Represents the This.databindtodatalist () of the event that occurred in DataList            ;        }

At this point, the binding information of the Edit template item will be displayed, we can change the name here, or cancel the edit, as follows


Finally, the code that cancels the modification function, the code of the update function, the deletion function, the event is Datalist1_cancelcommand, Datalist1_updatecommand , Datalist1_deletecommand.

protected void Datalist1_cancelcommand (object source, DataListCommandEventArgs e)//E represents the information that DataList passes to the function.  {datalist1.edititemindex =-1;        When the EditItemIndex property value is-1, the EditItemTemplate template databindtodatalist () is not displayed; } protected void Datalist1_updatecommand (object source, DataListCommandEventArgs e) {string ID =datalist1.datakeys[e.item.itemindex].             ToString (); String name = ((TextBox) E.item.findcontrol ("Txtname")).             Text;             SqlConnection con = db.createconnection ();             SqlCommand cmd = new SqlCommand ("Update person set personname= '" +name+ "' Where pid= '" +id+ "'", con); Cmd.             ExecuteNonQuery ();             Datalist1.edititemindex =-1;        Databindtodatalist ();  } protected void Datalist1_deletecommand (object source, DataListCommandEventArgs e) {string ID = Datalist1.datakeys[e.item.itemindex].            ToString (); SqlConnection con = db.createconnection ();           SqlCommand cmd = new SqlCommand ("Delete from person where pid= '" + ID + "'", con); Cmd.            ExecuteNonQuery ();            Datalist1.edititemindex =-1;        Databindtodatalist (); }




Summarize


The DataList control implements the operation of the person table in the database, implements the view details, modifies the operation, and the approximate process is to modify the data bound in each template of the DataList control, then wait for the specific event to display the contents of the template, and then manipulate the data. When the data adapter Dateadapter object populates data from the data source into a dataset, I can add the primary key to the DataKeys collection of DataList with the Datalist.datakeyfield= primary key field name statement. The primary key of the data item to be edited can then be removed from the collection when we want to modify the data, and the statement is Datalist1.datakeys[e.item.itemindex]. This allows us to modify the data items in the DataList table as we like.


Related Article

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.