C # several methods to bind DropDownList to add new data,

Source: Internet
Author: User

C # several methods to bind DropDownList to add new data,

First: manually bind data to the foreground (applicable to fixed data items)

<Asp: DropDownList ID = "DropDownList1" runat = "server"> <asp: ListItem Value = "1"> Nanjing </asp: ListItem> <asp: listItem Value = "2"> Yangzhou </asp: ListItem> <asp: ListItem Value = "3"> Xuzhou </asp: ListItem> <asp: listItem Value = "4"> Suzhou </asp: ListItem> </asp: DropDownList>

Type 2: dynamic binding in the background

DataTable dt = new DataTable (); // The central idea is to bind the data source from the drop-down list to a table (no value is assigned to the table here) DropDownList1.DataSource = dt. defaultView; // set the field name corresponding to the DropDownList space display item. Assume that there are two columns in the table, one is bound to the Text of the drop-down list, and the other is bound to ValueDropDownList1.DataValueField = dt. columns [0]. columnName; DropDownList1.DataTextField = dt. columns [1]. columnName; DropDownList1.DataBind ();

Third: custom addition

// Method 1: Perform ListItem li = new ListItem (); li. text = "Nanjing"; li. value = "1"; DropDownList1.Items. add (li); // Method 2: ListItem () the first parameter is the Value of Text, and the second parameter is the Value of Value ListItem li = new ListItem ("Yangzhou ", "2"); DropDownList1.Items. add (li); // method 3: One-Step DropDownList1.Items. add (new ListItem ("Xuzhou", "3"); // Method 4: (cyclically Add) string [] city = {"Nanjing", "Yangzhou ", "Xuzhou", "Suzhou"}; for (int I = 0; I <city. length; I ++) {DropDownList1.Items. insert (I, city [I]); DropDownList1.Items [I]. value = I. toString ();}

 

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.