您需要处理后面代码中的所有内容(在索引更改时选择/取消选择行)。这是基于您的设置的示例:
<asp:GridView DataKeyNames="EmpID"
SelectedRowStyle-BackColor="Yellow" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged"
runat="server" DataSourceID="sourceEmployees" AutoGenerateColumns="False"
AutoGenerateSelectButton="true" AllowSorting="true"
OnRowDataBound="test_RowDataBound" >
上面,我添加了两个事件处理程序,一个 forOnRowDataBound
和一个 for OnSelectedIndexChanged
。我还添加了DataKey
以跟踪所选员工 ID。
现在,在后面的代码中,这两种方法看起来像这样:
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["key"]= test.SelectedDataKey.Value;//Keep track of selected employee by ID
}
protected void test_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = e.Row.DataItem as DataRowView;
if (row.Row.Field<int>("EmpID") == (ViewState["key"] != null ? (int)ViewState["key"] : -1))
{
test.SelectedIndex = e.Row.RowIndex;
//Setting the selected Index is not enough, you need to programmatically
//set the color as well. Since I used Yellow on my markup, I use the same here
e.Row.BackColor = System.Drawing.Color.Yellow;
}
}
}