您可以使用OnRowDataBound
事件向GridView添加属性。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//add the current row number
e.Row.Attributes.Add("rowNumber", e.Row.RowIndex.ToString());
//add an item from the database
e.Row.Attributes.Add("itemID", DataBinder.Eval(e.Row.DataItem, "database_id").ToString());
//or add a click directy and redirect with javascript
e.Row.Attributes.Add("onclick", "location.href='/newPage.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "database_id").ToString() + "'");
}
}
如果你没有使用我的代码片段中的第三个属性,你需要处理行点击clientside。你可以用jQuery来做到这一点。
<script type="text/javascript">
$(document).ready(function() {
$("#<%= GridView1.ClientID %> tr").click(function() {
var rowNumber = $(this).attr("rowNumber");
var itemID = $(this).attr("itemID");
alert("This is row number: " + rowNumber + ". It has ID: " + itemID);
})
});
</script>
你想对“新选择的行”做什么?如果你需要在代码后面完成某些事情,你需要回传。如果是这样,你可以使用[UpdatePanel](https://msdn.microsoft.com/en-us/library/bb399001.aspx)。如果你需要在前端做某些事情,那么只能采取另一种方法。 – VDWWD
我只需要知道哪个索引被点击了,所以我可以去选择的项目的详细页面,如果页面刷新它做了几个API调用,这减慢了网站的速度,我会看看更新面板,谢谢 – Litrico