欢迎光临
我们一直在努力

GridView根据值的变化改变行列样式-.NET教程,评论及其它

建站超值云服务器,限时71元/月

我看到论坛中有询问关于如何在gridview随某行某列值的改变时(这些值是空的或不是空的或是其它某些值等),其背景色及文本颜色也随之改变。这篇文章便论述这个问题。

  根据某列的值改变其样式最好的方法是在gridview的datarowbound事件中想办法。在gridview中的行绑定数据后将立即执行datarowbound事件。datarowbound事件使用gridviewroweventargs类作为事件变量。通过事件变量你能够利用gridviewroweventargs属性操作已经绑定数据的行。

protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
 gridviewrow row = e.row;
}

  row将返回tablerow类中的一个gridviewrow对象。

  绑定的row有几种不同的类型。例如:datarow, emptydatarow, footer, header, pager 和 separator。通过gridview的rowtype属性可以得到当前行的行类型。rowtype是一组datacontrolrow枚举。

  看下面的代码示例,检测gridview列出的行是否为一个标准类型的行。

protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
 if (e.row.rowtype == datacontrolrowtype.datarow)
 {
  //do something!
 }
}

  可以使用row的cells属性得到其cells,它将返回一个tablecellcollection对象。然后通过tablecellcollection索引得到特定的cells。tablecellcollection索引将返回一个tabelcell对象,对应于row中的一个cell:

protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
 if (e.row.rowtype == datacontrolrowtype.datarow)
 {
  string value = e.row.cells[0].text;
 }
}

  现在你已经明白了如何得到gridview中某行某列的值,那么根据值的变化改变其样式就比较容易了。以下示例使用 northwind 数据库,通过检测第四列(unitprice)的值是否大于10将其颜色改变为红色。

<%@ page language=”c#”%>
<%@ import namespace=”system.drawing” %>

<!doctype html public “-//w3c//dtd xhtml 1.1//en” “http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd”>

<script runat=”server”>
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
 if (e.row.rowtype == datacontrolrowtype.datarow)
 {
  if (decimal.parse(e.row.cells[3].text) > 10)
   e.row.cells[3].backcolor = color.red;
 }
}

</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>untitled page</title>
</head>
<body>
 <form id=”form1″ runat=”server”>
 <div>
  <asp:gridview id=”gridview1″ runat=”server” datasourceid=”sqldatasource1″ autogeneratecolumns=”false”
datakeynames=”productid” onrowdatabound=”gridview1_rowdatabound”>
  <columns>
   <asp:boundfield readonly=”true” headertext=”productid” insertvisible=”false” datafield=”productid”
sortexpression=”productid” />
   <asp:boundfield headertext=”productname” datafield=”productname” sortexpression=”productname” />
   <asp:boundfield headertext=”quantityperunit” datafield=”quantityperunit” sortexpression=”quantityperunit” />
   <asp:boundfield headertext=”unitprice” datafield=”unitprice” sortexpression=”unitprice” />
  </columns>
 </asp:gridview>
<asp:sqldatasource id=”sqldatasource1″ runat=”server” selectcommand=”select [productid], [productname], [quantityperunit], [unitprice] from [alphabetical list of products]”

connectionstring=”<%$ connectionstrings:appconnectionstring1 %>” />

</div>
</form>
</body>
</html>

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » GridView根据值的变化改变行列样式-.NET教程,评论及其它
分享到: 更多 (0)