看到一個網(wǎng)友,有論壇上問及,動態(tài)的生成checkbox控件,在文本框中輸入一個“花”字,點一下“生成”按鈕,就會在下面生成一個checkbox,它的text屬性是“花”。再輸入一個“鳥”,點一下按鈕,就會生成第二個checkbox控件,text屬性是“鳥”...
Insus.NET的解決方法很簡單,就是每次在文本框輸入的值都存起來,然后把這些數(shù)據(jù)綁定至一個CheckBoxList控件上就行了。
詳細,先創(chuàng)建一個對象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Letter /// </summary> namespace Insus.NET { public class Letter { private string _Name; public string Name { get { return _Name; } set { _Name = value; } } public Letter() { } public Letter( string name) { this ._Name = name; } } } |
創(chuàng)建一個實體,這個實體你可以把它開發(fā)成可以操作性,如添加,編輯,更新,刪除或是獲取數(shù)據(jù)集,等等...
在本例中,Insus.NET只實添加以及獲取數(shù)據(jù)的兩個方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for LetterEntity /// </summary> namespace Insus.NET { public class LetterEntity { private List<Letter> _Letter = new List<Letter>(); public void Add(Letter l) { this ._Letter.Add(l); } public IEnumerable<Letter> Letters { get { return this ._Letter; } } } } |
萬事俱備,只差ASPX的實現(xiàn)了,創(chuàng)建一個aspx的網(wǎng)頁:
在ASPX.cs代碼頁中,你可以實現(xiàn)所需要的功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Insus.NET; public partial class Default2 : System.Web.UI.Page { LetterEntity le = new LetterEntity(); protected void Page_Load( object sender, EventArgs e) { if (!IsPostBack) { Data_Binding(); } le = TemporaryLetters; } private void Data_Binding() { this .CheckBoxList1.DataSource = le.Letters; this .CheckBoxList1.DataTextField = "Name" ; this .CheckBoxList1.DataBind(); } protected void Button1_Click( object sender, EventArgs e) { Letter l = new Letter(); if (! string .IsNullOrEmpty( this .TextBox1.Text.Trim())) l.Name = this .TextBox1.Text.Trim(); le.Add(l); TemporaryLetters = le; Data_Binding(); } public LetterEntity TemporaryLetters { get { if (Session[ "LetterEntity" ] == null ) return new LetterEntity(); else return (LetterEntity)Session[ "LetterEntity" ]; } set { Session[ "LetterEntity" ] = value; } } } |
你也許覺得很復雜,因為涉入存儲數(shù)據(jù)的問題。如果你把數(shù)據(jù)直接存入數(shù)據(jù)庫的話,你可以在上面#6步中把填寫的值存入數(shù)據(jù)庫中,在#4步中,去讀取數(shù)據(jù)庫的數(shù)據(jù)綁定給CheckBoxList控件即可。
以上所述是小編給大家介紹的Asp.net中使用文本框的值動態(tài)生成控件的方法的相關知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網(wǎng)站的支持!