要根據(jù)DataTable
中的不同值為asp:DataGrid
中的不同行或單元格設(shè)置不同的顏色,可以在服務(wù)器端代碼中根據(jù)數(shù)據(jù)綁定的時(shí)機(jī)來(lái)動(dòng)態(tài)設(shè)置樣式。以下是一個(gè)示例,演示如何根據(jù)DataTable
中的不同值為asp:DataGrid
的不同行設(shè)置不同的背景顏色
<asp:DataGrid ID="dataGrid" runat="server" AutoGenerateColumns="False" OnItemDataBound="dataGrid_ItemDataBound">
? ? <Columns>
? ? ? ? <asp:BoundColumn DataField="ID" HeaderText="ID" />
? ? ? ? <asp:BoundColumn DataField="Name" HeaderText="Name" />
? ? ? ? <asp:BoundColumn DataField="Age" HeaderText="Age" />
? ? </Columns>
</asp:DataGrid>
?
在上面的ASP.NET代碼中,我們創(chuàng)建了一個(gè)asp:DataGrid
,它有三個(gè)列:ID、Name和Age。
接下來(lái),在服務(wù)器端代碼中,可以使用OnItemDataBound
事件來(lái)為每一行設(shè)置不同的顏色。以下是服務(wù)器端代碼的示例:
protected void Page_Load(object sender, EventArgs e)
{
? ? if (!IsPostBack)
? ? {
? ? ? ? // 創(chuàng)建一個(gè)示例的DataTable
? ? ? ? DataTable dt = new DataTable();
? ? ? ? dt.Columns.Add("ID", typeof(int));
? ? ? ? dt.Columns.Add("Name", typeof(string));
? ? ? ? dt.Columns.Add("Age", typeof(int));
? ? ? ? // 向DataTable添加一些示例數(shù)據(jù)
? ? ? ? dt.Rows.Add(1, "Alice", 25);
? ? ? ? dt.Rows.Add(2, "Bob", 30);
? ? ? ? dt.Rows.Add(3, "Charlie", 35);
? ? ? ? // 將DataTable綁定到DataGrid
? ? ? ? dataGrid.DataSource = dt;
? ? ? ? dataGrid.DataBind();
? ? }
}
protected void dataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
? ? if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
? ? {
? ? ? ? // 獲取當(dāng)前行的數(shù)據(jù)
? ? ? ? DataRowView rowView = (DataRowView)e.Item.DataItem;
? ? ? ? int age = Convert.ToInt32(rowView["Age"]);文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-699274.html
? ? ? ? // 根據(jù)不同的Age值設(shè)置不同的顏色
? ? ? ? if (age < 30)
? ? ? ? {
? ? ? ? ? ? e.Item.BackColor = System.Drawing.Color.Yellow;
? ? ? ? }
? ? ? ? else if (age >= 30 && age < 40)
? ? ? ? {
? ? ? ? ? ? e.Item.BackColor = System.Drawing.Color.LightGreen;
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? e.Item.BackColor = System.Drawing.Color.LightBlue;
? ? ? ? }
? ? }
}
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-699274.html
到了這里,關(guān)于C#根據(jù)DataTable中的不同值為asp:DataGrid中的不同行或單元格設(shè)置不同的顏色的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!