我正在使用下面的GetPostBackClientHyperlink来填充文本框,其中包含有关行选择的相关信息。我还希望在回发后突出显示所选行。第二个属性将突出显示该行,但不会回发。我似乎无法让他们一起工作。
有什么想法吗?
aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
//e.Row.Attributes["onclick"] = string.Format("RowSelect({0});", e.Row.RowIndex);
}
答案 0 :(得分:3)
您必须在行onclick后回发后添加突出显示,如下所示:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
BindData();//Your method to set datasource anddatabind GridView1
GridView1.Rows[index].Attributes.Add("style","background-color:yellow");
// Even better add a class here so that you have more control from css
// GridView1.Rows[index].Attributes.Add("class", "mycustomclass");
}
您可以从GridView1_RowDataBound()
移动注释行:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
编辑:
这是我的标记, WebForm3.aspx :
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="GridViewTest.WebForm3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand">
</asp:GridView>
</div>
</form>
</body>
</html>
代码, WebForm3.aspx.cs :
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace GridViewTest
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
var lstItems = new List<ListItem>()
{
new ListItem {Text ="Items 1", Value ="1"},
new ListItem {Text ="Items 2", Value ="2"},
new ListItem {Text ="Items 3", Value ="3"},
new ListItem {Text ="Items 4", Value ="4"}
};
GridView1.DataSource = lstItems;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
//e.Row.Attributes["onclick"] = string.Format("RowSelect({0});", e.Row.RowIndex);
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
BindData();
GridView1.Rows[index].Attributes.Add("style", "background-color:yellow");
GridView1.Rows[index].Attributes.Add("class", "mycustomclass");
}
}
}
点击一行后,这是我突出显示的GridView:
如果仍然无法使用它,可以下载测试项目以与您的代码进行比较。测试项目是here。