用Javascript可以实现对GridView中某一行选择,而无需进行页面的刷新。
首先要在GridView的onrowdatabound的event handler中为GridView中的每一行onclick绑定event handler (Javascript)。假如GridView代码如下:
<asp:GridView runat="server" id="GridViewCategory" AutoGenerateColumns="False"
Width="100%" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid"
BorderWidth="3px" CellPadding="4" CellSpacing="2"
ForeColor="Black" onrowdatabound="GridViewCategory_RowDataBound">
<RowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Category" />
Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
asp:GridView>
onrowdatabound的event handler代码如下:
protected void GridViewCategory_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ID = e.Row.Cells[0].Text;
e.Row.Attributes.Add("onclick", "GridView_selectRow(this, '" + e.Row.Cells[0].Text + "')");
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
最后,GridView中每一行的onclick event handler的Javascript代码如下:
<script type="text/javascript">
var lastRowSelected;
function GridView_selectRow(row, description) {
if (lastRowSelected != row) {
if (lastRowSelected != null) {
lastRowSelected.style.backgroundColor = 'White';
lastRowSelected.style.color = 'Black';
}
}
row.style.backgroundColor = '#000099';
row.style.color = 'White';
lastRowSelected = row;
document.getElementById("<%=TextBoxCategory.ClientID%>").value = description;
}
script>