aspx
<script type="text/javascript"> var oldColor; function SetNewColor(Source) { oldColor = Source.style.backgroudColor; Source.style.backgroudColor = "#FFCCFF"; } function SetOldColor(Source) { Source.style.backgroudColor = oldColor; } function ShowPhoto(url) { document.getElementById("Image1").src= url; } </script> <body> <form id="form1" runat="server"> <div> <asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound"> <ItemTemplate> <table id="myTable" border="1" cellpadding="5" cellspacing="0" runat="server" οnmοuseοver='this.style.backgroundColor="#ff0000"'> <tr > <td> 圖片ID: <asp:Label ID="Label1" runat="server" Text=""><%#Eval("id")%></asp:Label> 圖片名稱: <asp:TextBox ID="txtimageName" runat="server" Text='<%#Eval("imageName")%>'></asp:TextBox> 圖片路徑: <asp:TextBox ID="txtimageUrl" runat="server" Text='<%#Eval("imageUrl")%>'></asp:TextBox> </td> </tr> </table> </ItemTemplate> </asp:ListView> <asp:Image ID="Image1" runat="server" /> <asp:DataPager ID="DataPager1" PagedControlID="ListView1" runat="server"> </asp:DataPager> </div> </form> </body>
aspx.cs
ShowImageBll ShowImageBll = new BLL.ShowImageBll(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindDL(); } } public void bindDL() { //繫結資料來源 DataSet ds = ShowImageBll.GetList(); ListView1.DataSource = ds; ListView1.DataBind(); } protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) //判斷目前的專案是否為一個資料專案 { ListViewDataItem curDataItem = (ListViewDataItem)e.Item; //把目前的專案轉化為一個ListViewDataItem DataRowView curRow = (DataRowView)curDataItem.DataItem;//把獲取的行轉化為DataRowView物件 int id = int.Parse(curRow["id"].ToString()); String imageUrl = ShowImageBll.getImageUrlByID(id); HtmlTable myTable = (HtmlTable)curDataItem.FindControl("myTable");//獲取ItemTemplate模板中的Table控制元件 myTable.Attributes.Add("onMouseOver", "SetNewColor(this);ShowPhoto('"+imageUrl+"');"); myTable.Attributes.Add("onMouseOut", "SetOldColor(this);ShowPhoto('image/20131129.jpg');"); } }
總結:
【1】前段HTML的Table控制元件 定義: <table id="myTable" border="1" cellpadding="5" cellspacing="0" runat="server">
後端獲取時:HtmlTable myTable = (HtmlTable)curDataItem.FindControl("myTable");//獲取ItemTemplate模板中的Table控制元件
(此時需要新增引用using System.Web.UI.HtmlControls;)
【2】ListViewDataItem curDataItem = (ListViewDataItem)e.Item; //把目前的專案轉化為一個ListViewDataItem
DataRowView curRow = (DataRowView)curDataItem.DataItem;//把獲取的ListViewItem物件所繫結的資料轉化為DataRowView物件
【3】遺留的問題:背景顏色的切換不起作用。函式SetNewColor(this)或者設定在aspx頁面內嵌javascript也不起作用