asp.net绑定label的示例代码
前台页面: <asp:Label ID=Label1 runat=server Text=’<%#GetName((sender as Label).ID.Substring(5)) %>’></asp:Label> <br /> <asp:Label ID=Label2 runat=server Text=’<%#GetName((sender as Label).ID.Substring(5)) %>’></asp:Label> <br /> <asp:Label ID=Label3 runat=server Text=’<%#GetName((sender as Label).ID.Substring(5)) %>’></asp:Label> <br /> <asp:Label ID=Label4 runat=server Text=’<%#GetName((sender as Label).ID.Substring(5)) %>’></asp:Label>
后台代码: IDictionary<int, string> Dic = new Dictionary<int, string>(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } public string GetName(object index) { //如果运算符的左边是非空的就返回左边,否则是右边! index = index ?? ; int key; int.TryParse(index.ToString(), out key); return Dic[key]; } public void BindData() { Dic.Add(1, 胡果); Dic.Add(2, 胡磊); Dic.Add(3, 俊文); Dic.Add(4, 刘皮); DataBind(); }
|