无法隐式转换类型'字符串' to' System.Web.UI.WebControls.Label'

时间:2014-04-03 18:44:49

标签: c# asp.net sql-server gridview

我将我的值从gridview传递到不同的页面行。数据库中gridview的表格如下:

 Create table Task
  (
    TaskId int Identity(1,1),
     Title varchar(100),
     Body varchar(500),
     Reward decimal(4,2),
    TimeAllotted int,
    PosterName varchar(100)
  )

详细信息页面的代码隐藏如下:

 protected void Page_Load(object sender, EventArgs e)
{
    if (this.Page.PreviousPage != null)
    {
        int rowIndex = int.Parse(Request.QueryString["RowIndex"]);
        GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
        GridViewRow row = GridView1.Rows[rowIndex];
        lblTaskId.Text = row.Cells[0].Text;
        lblTitle.Text = row.Cells[1].Text;
        lblBody.Text = row.Cells[2].Text;
        lblReward.Text = row.Cells[3].Text;
        lblTimeAllotted = row.Cells[4].Text;
        lblPosterName = row.Cells[5].Text;


    }
}

它根据需要显示所有内容但是当我在gridview的特定行中单击“查看任务”时,我得到一个异常不能隐式地将类型'string'转换为'System.Web.UI.WebControls.Label'。例外情况发生在最后两行,即

    lblTimeAllotted = row.Cells[4].Text;
    lblPosterName = row.Cells[5].Text;

我该如何纠正?

3 个答案:

答案 0 :(得分:3)

试试这个:

lblTimeAllotted.text = row.Cells[4].Text;
lblPosterName.text = row.Cells[5].Text;

您无法为文本设置标签。您需要设置标签的文本属性

答案 1 :(得分:1)

您无法将string设置为Label。您必须将值设置为两个标签的属性Text

lblTimeAllotted.Text = row.Cells[4].Text;
lblPosterName.Text = row.Cells[5].Text;

答案 2 :(得分:1)

在您的代码中,您有:

    lblTaskId.Text = row.Cells[0].Text;
    lblTitle.Text = row.Cells[1].Text;
    lblBody.Text = row.Cells[2].Text;
    lblReward.Text = row.Cells[3].Text;

其次是:

lblTimeAllotted = row.Cells[4].Text;
lblPosterName = row.Cells[5].Text;

我认为你的意思是:

lblTimeAllotted.Text = row.Cells[4].Text;
lblPosterName.Text = row.Cells[5].Text;

您看到异常的原因是.NET正在尝试将您的标签对象更改为单元格的字符串值,这显然是荒谬的。看起来像一个简单的错字:)