How to set background color in datatable using code?

I bind my data to datatable and then bind it to datagrid. I want some datatable rows of data to be highlighted. How can we do this with code?

+3
source share
3 answers

You need to connect to the ItemDataBound DataGrid event to dynamically set which you want.

In your HTML, set the OnItemDataBound DataGrid attribute to the server event.

<asp:DataGrid id="ItemsGrid" runat="server"
           ...
           OnItemDataBound="Item_Bound">

Then connect the server side event handler:

void Item_Bound(Object sender, DataGridItemEventArgs e) 
{
  // some code to handle each bound item
}

Then you can flip the colors based on the ListItemType enumeration:

if(e.Item.ItemType == ListItemType.Item)
   e.Item.BackColor = Color.Red;
else if (e.Item.ItemType == ListItemType.AlternatingItem)
   e.Item.BackColor = Color.Blue
+5
source

, :

foreach (DataGridItem item in DataGrid1.Rows) {
    item.BackColor = Color.Red;
}

foreach, :

counter = 0;
foreach (DataGridItem item in DataGrid1.Rows) {
    if (counter % 2 == 0)
        item.BackColor = Color.Black;
    else
        item.BackColor = Color.Red;

    ++counter;
}

, RPM1984, OnItemDataBound, ( ),

ASPX:

<asp:DataGrid ID="DataGrid1" OnItemDataBound="ItemDataBound" runat="server">

Code-:

public void ItemDataBound(object sender, DataGridItemEventArgs e) {
        e.Item.BackColor = Color.Red;
}

- , , , , OnItemDataBound BackColor:

Code-:

public void ItemDataBound(object sender, DataGridItemEventArgs e) {
        SalesPosition salesItem = e.Item.DataItem as SalesPosition;

        if(salesItem == null) return;

        if(salesItem.Type == SalesPositionType.Invoice)
            e.Item.BackColor = Color.Yellow;

        else if(salesItem.Type == SalesPositionType.Receipt)
            e.Item.BackColor = Color.Green;
    }
+5

ASP OnDatabound:

TAG , Datarow

 <asp:GridView ID="gvAps" BackColor="Yellow" runat="server" HeaderStyle-CssClass="GridView_Entete" OnRowDataBound="RowDataBound" />

- :

 protected void RowDataBound(object sender, GridViewRowEventArgs e)
 {   
            DataRowView drv = (DataRowView)e.Row.DataItem;
            if (drv["INVOICES/RECEIPTS "].ToString()) == "INVOICE" )

            {
            e.Row.Attributes.Remove("Class");
            e.Row.Attributes.Add("Class", "GridView_New");
            }
  }

css .

 protected void RowDataBound(object sender, GridViewRowEventArgs e)
        {        
            DataRowView drv = (DataRowView)e.Row.DataItem;
            if (drv["INVOICES/RECEIPTS "].ToString()) == "INVOICE" )
                 }
                    e.Item.BackColor = Color.Green;
                 }

         }
+1

Source: https://habr.com/ru/post/1755908/


All Articles