[英]For a Windows Forms Application using `DataGridView`, how can I check a value in my DataSource and change the color of a separate cell?
[英]How can I change the color of a cell in my datareader?
我正在遍歷我的數組並使用下面的代碼創建行。 狀態返回真或假。 如果它是假的,我想將該特定單元格的背景顏色設置為紅色。 如何更改單元格的顏色?
<asp:DataGrid ID="DataGrid1" runat="server" AlternatingItemStyle-BackColor="#e4e4e4" AutoGenerateColumns="false" >
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="Name" >
<HeaderStyle BackColor="#4B6C9E" ForeColor="White" />
<ItemStyle Width="240px" Wrap="True" />
</asp:BoundColumn>
<asp:BoundColumn DataField="Status" HeaderText="Coupon Status" >
<HeaderStyle BackColor="#4B6C9E" ForeColor="White" />
<ItemStyle Width="20px" Wrap="True" />
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
后面的代碼:
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Status");
// Looping through the rows here.
DataSet datareader = db.ExecuteDataSet(command);
DataRow dr = dt.NewRow();
dr["Name"] = datareader.Tables[0].Rows[0]["Name"];
dr["Status"] = datareader.Tables[0].Rows[0]["Status"];
dt.Rows.Add(dr);
DataGrid1.DataSource = dt;
DataBind();
DataGrid 上有一個 ItemDataBound 事件,或類似的事件。 掛鈎,您應該能夠檢查狀態列值並相應地設置單元格顏色。
使用模板獲取自定義設置,
<ItemTemplate>
<asp:Panel ID="pnlCol1" runat="server">
<asp:Label ID="LabelName" runat="server"
Text='<%# Eval("Name") %>' OnDataBind="LabelName_DataBind" />
</asp:Panel>
</ItemTemplate>
protected void LabelName_DataBind(object sender, EventArgs e)
{
Label label = (Label)sender;
Panel panel = (Panel)label.NameingContainer;
// Set color here to panel
panel.BackColor = Color.Red;
}
或者您可以使用 PreRender 事件。 這取決於您的需求。
將 onitemdatabound 事件添加到您的網格
<asp:DataGrid ID="DataGrid1" runat="server"
AlternatingItemStyle-BackColor="#e4e4e4" AutoGenerateColumns="false"
onitemdatabound="DataGrid1_ItemDataBound" >
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="Name" >
<HeaderStyle BackColor="#4B6C9E" ForeColor="White" />
<ItemStyle Width="240px" Wrap="True" />
</asp:BoundColumn>
<asp:BoundColumn DataField="Status" HeaderText="Coupon Status" >
<HeaderStyle BackColor="#4B6C9E" ForeColor="White" />
<ItemStyle Width="20px" Wrap="True" />
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
如果狀態為假,您可以在代碼隱藏中設置狀態列的背景顏色。
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var status = Convert.ToBoolean(((DataRowView)e.Item.DataItem).Row.ItemArray[1]);
if (!status)
{
e.Item.Cells[1].BackColor = System.Drawing.Color.Red;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.