看到一個網友,有論壇上問及,動態(tài)的生成checkbox控件,在文本框中輸入一個“花”字,點一下“生成”按鈕,就會在下面生成一個checkbox,它的text屬性是“花”。再輸入一個“鳥”,點一下按鈕,就會生成第二個checkbox控件,text屬性是“鳥”...
![](/d/20211017/a9eb3d8193959089e130900aa1bdd25e.gif)
Insus.NET的解決方法很簡單,就是每次在文本框輸入的值都存起來,然后把這些數(shù)據綁定至一個CheckBoxList控件上就行了。
詳細,先創(chuàng)建一個對象:
![](/d/20211017/89078eeae81ede8252104007838a38b0.gif)
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ù)據集,等等...
在本例中,Insus.NET只實添加以及獲取數(shù)據的兩個方法:
![](/d/20211017/bfab42c0765d12d7d3754679ef915950.gif)
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 ListLetter> _Letter = new ListLetter>();
public void Add(Letter l)
{
this._Letter.Add(l);
}
public IEnumerableLetter> Letters
{
get {
return this._Letter;
}
}
}
}
萬事俱備,只差ASPX的實現(xiàn)了,創(chuàng)建一個aspx的網頁:
![](/d/20211017/66535a18c380f7003680a081ce052ef3.gif)
在ASPX.cs代碼頁中,你可以實現(xiàn)所需要的功能:
![](/d/20211017/a5bd3fb8c712abe8581092a02eccfb46.gif)
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ù)據的問題。如果你把數(shù)據直接存入數(shù)據庫的話,你可以在上面#6步中把填寫的值存入數(shù)據庫中,在#4步中,去讀取數(shù)據庫的數(shù)據綁定給CheckBoxList控件即可。
以上所述是小編給大家介紹的Asp.net中使用文本框的值動態(tài)生成控件的方法的相關知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
您可能感興趣的文章:- ASP.NET 廣告控件AdRotator的使用方法與實例
- ASP.NET筆記之廣告控件的使用方法
- ASP.NET 網站開發(fā)中常用到的廣告效果代碼
- 獲取asp.net服務器控件的客戶端ID和Name的實現(xiàn)方法
- asp.net控件DataList分頁用法
- ASP.NET項目開發(fā)中日期控件DatePicker如何使用
- ASP.NET中 ObjectDataSource控件的DataObjectTypeName屬性
- ASP.NET的廣告控件AdRotator用法分析