基本的に: コード ビハインドでは、セルごとに onclick スクリプトを設定し、セルの座標と結果のテキスト ボックスを渡します。
aspx では、js スクリプトはクリックされたセルの座標をテキスト ボックスに書き込み、テーブル内のすべてのセルを反復して色を白に設定し、最後にクリックされたセルの背景色を赤に設定します。
aspx コード:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestEvidenziazione.aspx.vb" Inherits="Web_Test_2010.TestEvidenziazione" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function highlight(my_row, cell, textbox) {
document.getElementById("<%=txtCellSelected.ClientID%>").value = my_row + ',' + cell;
var table = document.getElementById("<%=GridView1.ClientID%>");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
col.style.backgroundColor = '#ffffff';
if (i == my_row && j == cell) {
col.style.backgroundColor = '#ff0000';
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtCellSelected" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" ShowHeader="false">
</asp:GridView>
</div>
</form>
</body>
</html>
vb.net コード:
Public Class TestEvidenziazione
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadData()
End Sub
Private Sub LoadData()
Dim list As New ArrayList
Dim row1 As New myRowClass
Dim row2 As New myRowClass
Dim row3 As New myRowClass
row1.a = "0,0"
row1.b = "0,1"
row1.c = "0,2"
row2.a = "1,0"
row2.b = "1,1"
row2.c = "1,2"
row3.a = "2,0"
row3.b = "2,1"
row3.c = "2,2"
list.Add(row1)
list.Add(row2)
list.Add(row3)
GridView1.DataSource = list
GridView1.DataBind()
End Sub
Private Class myRowClass
Public Property a As String
Public Property b As String
Public Property c As String
End Class
Private Sub GridView1_PreRender(sender As Object, e As System.EventArgs) Handles GridView1.PreRender
For index_row = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(index_row).RowType = DataControlRowType.DataRow Then
For index_cell = 0 To GridView1.Rows(index_row).Cells.Count - 1
GridView1.Rows(index_row).Cells(index_cell).Attributes("onclick") = "highlight(" & index_row.ToString & "," & index_cell.ToString & ", " & txtCellSelected.ClientID & "); "
Next
End If
Next
End Sub
End Class