在 DataList 的每一列放置 TextBox,當使用者焦點進入時,自動帶入預設值並顯示當前行號。這在批次資料輸入、樣板套用等情境相當實用。
<asp:DataList ID="dlItemGeneral" runat="server" CellPadding="0" CellSpacing="0" Width="100%"
OnItemDataBound="dlItemGeneral_ItemDataBound">
<ItemTemplate>
<asp:Table ID="Table1" runat="server" CssClass="table">
<asp:TableRow>
<asp:TableCell CssClass="tableTemplateCell" Width="15%">
物料編碼 <%# Eval("ItemCode") %>
</asp:TableCell>
<asp:TableCell CssClass="tableCell" Width="30%">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell CssClass="tableCell" Width="55%"></asp:TableCell>
</asp:TableRow>
</asp:Table>
</ItemTemplate>
</asp:DataList>
protected void dlItemGeneral_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox textBox = e.Item.FindControl("TextBox1") as TextBox;
if (textBox != null)
{
// 註冊 OnFocus 客戶端事件,呼叫兩個靜態方法
textBox.Attributes.Add("OnFocus",
"alert('" + GetRowNumber(e) + "'); this.value='" + GetTextBox(e) + "';");
}
}
}
private static string GetRowNumber(DataListItemEventArgs e)
{
return "當前行號為 " + (e.Item.ItemIndex + 1).ToString();
}
private static string GetTextBox(DataListItemEventArgs e)
{
return "這是從靜態方法獲取值,當前行索引為:" + e.Item.ItemIndex.ToString();
}
Attributes.Add 將 JavaScript 字串寫入 onfocus,注意單引號跳脫。e.Item.ItemIndex 從 0 起算,顯示時通常 +1。OnFocus 僅呼叫函式並傳遞行號參數。HttpUtility.JavaScriptStringEncode)。data-* 屬性儲存行號,由統一事件處理器處理,分離關注點。同樣技巧可用於:GridView、Repeater、ListView 等繫結控制項,只需對應 RowDataBound 或 ItemDataBound 事件即可。