不能将类型“字符串”隐式转换为“System.Web.UI.WebControls.Label”

本文关键字:字符串 Web System UI Label WebControls 类型 不能 转换 | 更新日期: 2023-09-27 17:56:23

我正在逐行将我的值从网格视图传递到不同的页面。数据库中网格视图的表如下所示:

 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;

    }
}

它根据需要显示所有内容,但是当我单击网格视图特定行中的"视图任务"时,出现异常 无法将类型"字符串"隐式转换为"系统.Web.UI.WebControls.Label"。异常发生在最后两行,即

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

我该如何纠正此问题?

不能将类型“字符串”隐式转换为“System.Web.UI.WebControls.Label”

试试这个:

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

不能为文本设置标签。您需要设置标签的文本属性

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

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

在你的代码中,你有:

    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 试图将标签对象更改为单元格的字符串值,这显然是荒谬的。看起来像一个简单的错别字:)