1.首先在前台dataGridview属性中增加onRowDataBound属性事件
2.然后在后台Observing_RowDataBound事件中增加代码
protected void Observing_RowDataBound(object sender, GridViewRowEventArgs e)
{
//首先判断是否是数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#eed6d6'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
此随笔参考原文 http://www.cnblogs.com/Ryan_j/archive/2010/10/04/1842038.html GridView72般绝技
3.下面是自己增加的内容【给GridView增加单击行事件,并获取单击行的数据填充到页面中的控件中】
e.Row.Attributes.Add("onclick", "getGridViewValue('" + strName + "','" + strSex + "','" + strAge + "','" + Server.UrlEncode(strDiag).Replace("+", "%20") + "')");
strDiag诊断这个字段有可能会出现有空格的现象,如果有空格,不编码传到前台js会报错,所以这里要编码。而vs编码后空格就会变成+号,所以这里要用Server.UrlEncode编码后并将+号替换为%20,前台js中接收并解码就成功了,单击GridView填充数据到Textbox控件中。
【最后附上代码】
【后台】
protected void Observing_RowDataBound(object sender, GridViewRowEventArgs e)
{ //首先判断是否是数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#eed6d6'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
int index = e.Row.DataItemIndex;
DataTable dt = (DataTable)ObservingGrid.DataSource;
string strName = dt.Rows[index][].ToString();
string strSex = dt.Rows[index][].ToString();
string strAge = dt.Rows[index][].ToString();
string strDiag = dt.Rows[index][].ToString();
//DY.Web.UI.Dialog.LhgDialog.Alert(this, "getGridViewValue('" + strName + "','" + strSex + "','" + strAge + "','" + Uri.EscapeDataString(strDiag) + "')", "");
e.Row.Attributes.Add("onclick", "getGridViewValue('" + strName + "','" + strSex + "','" + strAge + "','" + Server.UrlEncode(strDiag).Replace("+", "%20") + "')"); } }
【js】
<script type="text/javascript">
function getGridViewValue(name, sex, age, diag) {
document.getElementById("TbName").value = name;
document.getElementById("DdlbSex").value = sex;
document.getElementById("TbAge").value = age;
document.getElementById("TbDiagnosis").value = decodeURI(diag);
}
</script>