c#中如何根据datagrid中绑定的不同数据,使datagrid显示不同颜色

解决方案 »

  1.   

    每绑定一次就重新设置一次TableStyles
      

  2.   

    // Provides the format for the given cell.
    private void SetCellFormat(object sender, DataGridFormatCellEventArgs e)
    {
    //conditionally set properties in e depending upon e.Row and e.Col
    bool discontinued = (bool) ((e.Column != 0) ? this.dataGrid1[e.Row, 0] : e.CurrentCellValue);
    //check is discontinued
    if(e.Column > 0 && (bool)(this.dataGrid1[e.Row, 0]))//discontinued)
    {
    e.BackBrush = this.disabledBackBrush;
    e.ForeBrush = this.disabledTextBrush;
    }
    else if(e.Column > 0 && e.Row == this.dataGrid1.CurrentRowIndex)//discontinued)
    {
    e.BackBrush = this.currentRowBackBrush;
    e.TextFont = this.currentRowFont;
    }
    else if(NeedToReorder(e.Row))
    {
    e.TextFont = this.alertFont;
    e.ForeBrush = this.alertTextBrush;
    e.BackBrush = this.alertBackBrush;
    }
    // Given a row, computes whether product needs to be reordered.
    //是否要突现(特征)行
    private bool NeedToReorder(int row)
    {
    int unitsInStock = (Int16) this.dataGrid1[row,  this.unitsInStockCol];
    int unitsOnOrder = (Int16) this.dataGrid1[row,  this.unitsOnOrderCol];
    int reorderLevel = (Int16) this.dataGrid1[row,  this.reorderLevelCol]; return (reorderLevel > (unitsInStock + unitsOnOrder));
    }
      

  3.   

    你是否要不同的数据,DataGrid的行显示不同的背景色?
    可以利用ItemDataBound事件。
    if(e.Item.ItemType == ListItemType.Item||e.Item.ItemType == ListItemType.AlternatingItem)
    {
        if(你的条件) e.Item.ForeColor=Color.Red;
    }
      

  4.   

    楼上说的是System.Web.UI.WebControls下的DataGrid控件
      

  5.   

    for(int i=0;i<DataGrid1.Items.Count;i++)
    {
    if(DataGrid1.Items[i].Cells[6].Text=="1")
    {
    System.Web.UI.WebControls.Style style=new System.Web.UI.WebControls.Style();
    style.CssClass="row01";
    DataGrid1.Items[i].MergeStyle(style);
    }
    else if(DataGrid1.Items[i].Cells[6].Text=="0")
    {
    System.Web.UI.WebControls.Style style=new System.Web.UI.WebControls.Style();
    style.BackColor=System.Drawing.ColorTranslator.FromHtml("#ffcc99");
    DataGrid1.Items[i].MergeStyle(style);
    }
    }