change background color of dropdown items at runti

2019-06-07 13:23发布

问题:

i have a dropdown cboVendor in which supplier name is coming now i want background colour to be red whose fullyAgg column(dt contains 11 columns in which fullagg is the 11th column) is coming as Zero.currently i am doing as shown in the below code but it is taking all of them a zero(which should not happen)

.aspx

<asp:DropDownList ID="cboVendor" runat="server" AppendDataBoundItems="True"
AutoPostBack="true"> <asp:ListItem Value="0">- Select Vendor -</asp:ListItem>
</asp:DropDownList>

c# code

DataTable dt = default(DataTable);
cboVendor.DataSource = dt;
cboVendor.DataTextField = "SupplierName";
cboVendor.DataValueField = "SupplierID";
cboVendor.DataBind();
cboVendor.SelectedIndex = 0;
foreach (ListItem item in cboVendor.Items) {
    if (dt.Rows(10)("fullyAgg") == 0) {
        item.Attributes.Add("style", "background-color:red;");
    }
}

回答1:

found the solution

DataView dv = dt.DefaultView;
dv.RowFilter = "fullyAgg=0";
foreach (DataRowView dr in dv) {
    foreach (ListItem item in cboVendor.Items) {
        if (dr("SupplierID").ToString() == item.Value.ToString()) {
            item.Attributes.Add("style", "background-color:red;");
        }
    }
}


回答2:

You may try this :

foreach (ListItem item in cboVendor.Items) {
//select row corresponding to current dropdown item
var selectedRow = from myRow in dt.AsEnumerable()
where myRow.Field<int>("SupplierID") == item.Value
select myRow;
//check fullyAgg column for selected row
if (selectedRow("fullyAgg") == 0) {
        item.Attributes.Add("style", "background-color:red;");
    }
}


回答3:

Couple of issues:

 if (dt.Rows(10)("fullyAgg") == 0) {

First: you make no iteration there, you are comparing the same value everytime.

Second: Rows(10) doesn't give you the 11nth column (row <> column !!!)

Third: make the foreach (a proper one) in cboVender_ItemDataBound function (which handles cboVender.ItemDataBound) so you can access the item's properties from there

Edit: how to do it? -> have you tried anything I said?

private void cboVender_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) {
     if ((e.Item.ItemType == ListItemType.Item)) {
         rowIndex = e.Item.ItemIndex;
          // here you have your row number, you can Access the value of that column and do whatever you want
     }         
 }