DataGrid的ItemDataBound事件

DATAGRID中,如果要對某些記錄進行格式化或者修飾,用到itemdatabound事件比較方便,
比如,要顯示某人的存款金額已經少於某個數額了,要用紅色來顯示等。itemdatabound事件發生在
數據綁定到datagrid後,而其內容發送到客戶端前。
比如
private void OnItemDataBound(object sender,
        System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
      if (e.Item.ItemType == ListItemType.Item ||  e.Item.ItemType == ListItemType.AlternatingItem)
       {
            Label lblBalance = (Label)e.Item.FindControl("dgLabel2");
           double dblBalance = Convert.ToDouble(lblBalance.Text);
           if(dblBalance < 0)
            e.Item.Cells[3].ForeColor = System.Drawing.Color.Red;
      
            Label lblCountry = (Label)e.Item.FindControl("dgLabel1");
             string strCountry = lblCountry.Text;

        if(strCountry == "USA" || strCountry == "Mexico" || strCountry == "Canada")
          {
            // Get a copy of the "dgLabel0" label that contains the
            // "CustomerID" value, we'll use it in the query string
            // for the popup
            Label lblID = (Label)e.Item.FindControl("dgLabel0");
            // ...convert it to a string
            string strID = lblID.Text;
            // Replace the "Country" value displayed in the datagrid
            // with "Jamaica", placed in a hyperlink who's onClick
            // event calls a javas cript "popup" window
            e.Item.Cells[2].Text = "<a href=/"popup.aspx?id=" + strID +
                "/" onClick=/"popup(this.href); return false;/">Jamaica</a>";
        }
    }
}


而itemcreated事件和它有些不同,itemcreated發生在itemdatabound事件前,當datagrid中的每一項創建了但沒
有數據時,所以不能用itemcreated事件來修改或者讀取數據

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章