我在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'。存在显式转换(是 你错过了一个演员?))
答案 0 :(得分:1)
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();
}
}
答案 1 :(得分:1)
向其添加显式转换
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();
}
}
答案 2 :(得分:0)
请更改方法定义内的第1行,如下所示:
Label lbltotal= e.Row.FindControl("lbltotal") as Label;
答案 3 :(得分:0)
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();
}
}
答案 4 :(得分:0)
由于您正在寻找Label
,因此您需要将Control
从FindControl
转发给它。您还应该检查行是否为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();
}
}