簡體   English   中英

從后面的代碼為gridview內部的標簽賦值

[英]Assigning value to the label which is inside gridview from code behind

我在gridview中調用了一個標簽,並希望從后面的代碼中為該標簽賦值,但是無法做到這一點。我已經創建了該gridview的rowbound,如下所示:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       Label lbltotal= e.Row.FindControl("lbltotal");
        String price=Session["price"].ToString();
        DataTable dt = GridView1.DataSource as DataTable;
       lbltotal.Text = dt.Compute("sum(price)", "").ToString();
    }

我收到這樣的錯誤:

(不能隱式地將類型'System.Web.UI.Control'轉換為'System.Web.UI.WebControls.Label'。存在顯式轉換(你是否錯過了演員?))

e.Row.FindControl返回System.Web.UI.Control ,這需要顯式地轉換為Label控件

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   Label lbltotal= e.Row.FindControl("lbltotal") as Label;

   if(lbltotal != null)
   {
     String price=Session["price"].ToString();
     DataTable dt = GridView1.DataSource as DataTable;
     lbltotal.Text = dt.Compute("sum(price)", "").ToString();
   }
}

添加顯式轉換

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       Label lbltotal= e.Row.FindControl("lbltotal") as Label; //explicit convert to label
       if(lbltotal != null)
         {
            String price=Session["price"].ToString();
            DataTable dt = GridView1.DataSource as DataTable;
           lbltotal.Text = dt.Compute("sum(price)", "").ToString();
         }
    }

請更改方法定義中的第1行,如下所示:

Label lbltotal= e.Row.FindControl("lbltotal") as Label;

你可以這樣做:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {      
  if (e.Row.RowType == DataControlRowType.DataRow)
   {
     Label lbltotal=(Label) e.Row.FindControl("lbltotal");
     String price=Session["price"].ToString();
     DataTable dt = GridView1.DataSource as DataTable;
     lbltotal.Text = dt.Compute("sum(price)", "").ToString();
   }
 }

由於您正在尋找Label您需要將從FindControl返回的Control為它。 您還應檢查該行是否為DataControlRowType.DataRow ,否則您還在頁眉和頁腳中查找標簽。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lbltotal= (Label)e.Row.FindControl("lbltotal");
        var allRows = ((DataRowView)e.Row.DataItem).Row.Table.AsEnumerable();
        decimal totalPrice = allRows.Sum(r => r.Field<decimal>("Price"));
        lbltotal.Text = totalPrice.ToString();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM