C#数据绑定控件中的DataSource属性浅谈

2019-05-20 13:38:50刘景俊


privatevoidBindData() 

Dictionary<string,int>dic=newDictionary<string,int>(); 
dic.Add("Jim",21); 
dic.Add("Tom",26); 
dic.Add("Bluce",33); 
dic.Add("Mary",18); 

Repeater1.DataSource=dic; 
Repeater1.DataBind(); 
}

HTML代码
程序代码

<asp:RepeaterIDasp:RepeaterID="Repeater1"runat="server">
<HeaderTemplate><table><tr><thscopethscope="col">姓名<th><th>年龄<th><tr><HeaderTemplate>
<ItemTemplate><tr><td><%#Eval("Key")%>td><td><%#Eval("value")%><td><tr><ItemTemplate>
<FooterTemplate><table><FooterTemplate>
<asp:Repeater>

<4>绑定对象集合,IList等。这个很是有用,在我们进行数据查询的时候,经常从数据库取出数据,为了方便操作,需要封装成对象,但是有的时候需要将这些对象以列表的形式显示出来,一种解决方案:对象转换为DataTable,另一种就是直接调用数据库。这两种方案,并不是很理想。而这里直接将对象集合直接绑定到数据显示控件,给我指明一条出路。其实,在PetShop4.0就是利用这一点,绑定ICollection或者IList。简单明了。
一个简单的用户类,包含两个公共属性。
程序代码

usingSystem; 
usingSystem.Data; 

///

///SummarydescriptionforUser 
///

publicclassUser 

privatestring_Name; 
publicstringName 

get{return_Name;} 
set{_Name=value;} 

privateint_Age; 
publicintAge 

get{return_Age;} 
set{_Age=value;} 

publicUser() 

// 
//TODO:Addconstructorlogichere 
// 

publicUser(stringname,intage) 

_Name=name; 
_Age=age; 

}


绑定对象集合:
IList
程序代码

privatevoidBindData() 

Useruser1=newUser("Jim",21); 
Useruser2=newUser("Tom",23); 
Useruser3=newUser("Bluce",33); 
Useruser4=newUser("Mary",18); 

IList<User>list=newList<User>(); 
list.Add(user1); 
list.Add(user2); 
list.Add(user3); 
list.Add(user4); 

Repeater1.DataSource=list; 
Repeater1.DataBind(); 
}

对应的Repeater绑定对象的公共属性:
C#数据绑定控件程序代码

<asp:RepeaterIDasp:RepeaterID="Repeater1"runat="server">
<HeaderTemplate>
<table>
<tr>
<thscopethscope="col">
姓名th>
<th>
年龄<th>
<tr>
<HeaderTemplate>
<ItemTemplate>
<tr>