根据数据表asp.net的标志列在运行时更改下拉项的背景颜色

我有一个下拉cboVendor ,其中供应商名称即将到来我想要背景颜色为红色,fullyAgg(dt contains 11 columns in which fullagg is the 11th column )将作为零。当前我正在做,如下面的代码所示但它将所有这些都归零(这不应该发生)

的.aspx

  - Select Vendor -  

c#代码

 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;"); } } 

找到了解决方案

 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;"); } } } 

你可以试试这个:

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

几个问题:

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

首先:你没有进行迭代,你每次都在比较相同的值。

第二:行(10)没有给你第11列(行<>列!!!)

第三:在cboVender_ItemDataBound函数(处理cboVender.ItemDataBound)中创建foreach(一个正确的),以便您可以从那里访问该项的属性

编辑:怎么做? – >你试过我说的话吗?

 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 } }