Mash
Mash

Reputation: 159

Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.Label'

I am passing my values from a gridview to a different page row-wise.The table for the gridview in the database is as follows:

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

the code -behind for the details page is as below:

 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;


    }
}

It displays everything as desired but when I click on 'view task' in a particular row of the gridview, I get an exception Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.Label'. The exception occurs on the last two lines i.e

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

How can I correct this?

Upvotes: 1

Views: 9348

Answers (3)

NWard
NWard

Reputation: 2086

In your code, you have:

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

Followed by:

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

I presume that what you actually mean is:

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

The reason you are seeing the exception is that .NET is trying to change your label objects to the string value of the cells, which is obviously nonsensical. Looks like a simple typo :)

Upvotes: 1

Guilherme Oliveira
Guilherme Oliveira

Reputation: 2026

You cannot set a string to a Label. You have to set the value to property Text of both labels:

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

Upvotes: 2

logixologist
logixologist

Reputation: 3834

Try this:

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

You cant set a label to a text. You need to set the text property of the label

Upvotes: 4

Related Questions