Google搜查列

 

2009年11月25日 星期三

C#.NET 根據GridView 的欄位值來改變顯示

GridView..::.RowDataBound Event

有時後在DataSource查詢出來的資料,利用GridView 顯示可能不合理想或想作多一點的改變

可以自己另外寫副程式,來改變顯示

比如有一個DateSource查詢出來是這樣子





學生\科目國文數學英文
小英506080
小明803350

但你想要把輸出時,不及格以紅字,粗體顯示,或咖別的處理,可以使用GridView 中的onrowdatabound 指定副程式




<script language="C#" runat="server">
protected void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{

if (e.Row.Cells[1].Text <= 59)
{
e.Row.Cells[1].Text = "<span style=\"color: #ff0033\"><b>" + e.Row.Cells[1].Text + "</b></span>";
}
if (e.Row.Cells[2].Text <= 59)
{
e.Row.Cells[2].Text = "<span style=\"color: #ff0033\"><b>" + e.Row.Cells[2].Text + "</b></span>";
}
if (e.Row.Cells[3].Text <= 59)
{
e.Row.Cells[3].Text = "<span style=\"color: #ff0033\"><b>" + e.Row.Cells[3].Text + "</b></span>";
}
}

}
</script>

<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="Select [name] as '學生\科目', [Chin] as '國文', [Math] as '數學', [Engl] as '英文' From [Results]"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server">
</asp:sqldatasource>

<asp:gridview id="Gridview1"
datasourceid="CustomersSqlDataSource"
onrowdatabound="CustomersGridView_RowDataBound"
runat="server">
</asp:gridview>

輸出:





學生\科目國文數學英文
小英506080
小明803350


參考文件:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx

Google Analytics