在後臺的GridView1_RowDataBound()方法添加代碼,最後代碼如下所示:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i;
//執行循環,保證每條數據都可以更新
for (i = 0; i < GridView1.Rows.Count; i++)//這裏如果i從0開始的話,那麼鼠標移動到數據行的第一行時,顏色並沒有改變,所以建議改爲 i = -1
{
//首先判斷是否是數據行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//當鼠標停留時更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
//當鼠標移開時還原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
}
前臺代碼:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>實現鼠標劃過改變GridView的行背景色 </title>
</head>
<body>
<form runat="server">
<div>
<asp:GridView runat="server" AutoGenerateColumns="False" DataKeyNames="身份證號碼"
DataSourceID="SqlDataSource1" AllowSorting="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="身份證號碼" HeaderText="身份證號碼" ReadOnly="True" SortExpression="身份證號碼" />
<asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" />
<asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址" />
<asp:BoundField DataField="郵政編碼" HeaderText="郵政編碼" SortExpression="郵政編碼" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource runat="server" ConnectionString="<%$"
SelectCommand="SELECT top 5 [身份證號碼], [姓名], [員工性別], [家庭住址], [郵政編碼] FROM [http]" DataSourceMode="DataReader"></asp:SqlDataSource>
</div>
</form>
</body>
</html>