前台頁面:
<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();
}