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

I have a datagrid

Label ID1 = (Label)(e.Item.FindControl("ID1"));

Label Name1 = (Label)(e.Item.FindControl("Name1"));

Label TableName = (Label)(e.Item.FindControl("TableName"));


No0w Iam trying to

TBTableName.Text = lblTableName;
                  tbid.Text = lblImageTypeID1;
                   tbnameordes.Text = lblImageName1;

I have tried l lbltablename.text,.tostring,convert.tostring() nthg is working.

Any clues?


11/11/2008 3:37:00 PM 72751 articles. 3 followers. Follow

8 Replies

Similar Articles

[PageSpeed] 54

Is lblTableName a label control? It it is then lblTableName.Text should work. The "T" in Text is uppercase.

Let Me Google That For You!
11/11/2008 4:37:15 PM

Its not working If the label is empty and I am trying to assign it to textbox





Is throwing error Is there a way that I can pass this label although it is empty



11/12/2008 12:30:12 AM

First off, can you please confirm that you are not using "text" with a lowercase "t".

Please post the exact code that you have from your code file, and exact error. Even if the label is empty, it should not throw the error that you posted.

What that error means is that you tried an assignment which tried to convert the Label control to string, instead of assigning its Text property value to a string variable.

Let Me Google That For You!
11/12/2008 1:08:22 PM

Dgview_RowDataBound(Object sender, GridViewRowEventArgs e)


lblImageTypeID = (Label)(e.Row.FindControl("lblImageTypeID"));

Label lblImageTypeName = (Label)(e.Row.FindControl("imageTypeName"));

this.ImageId = lblImageTypeID; (imageid is a label some times I am assigning it to text boxes)

this.ImageName = lblImageTypeName;


Dgview_RowCommand(object source, GridViewCommandEventArgs e)


if (e.CommandName == "Edit")






I am getting

System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 467:        if (e.CommandName == "Edit")
Line 468:        {
Line 469:            Response.Write(ImageId.Text);


11/12/2008 2:02:08 PM

Can you put breakpoints and run in this in debug mode to see what is happening?

Let Me Google That For You!
11/12/2008 2:07:56 PM

I tried

ImageId.Text = lblImageTypeID.Text;

ImageName.Text = lblImageTypeName.Text;

also still the error is there

11/12/2008 2:12:27 PM

Did you try what I suggested?

Let Me Google That For You!
11/12/2008 2:21:00 PM

Hi krishnada25 ,

I think it should work with the help of bullpit .


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            DataRowView drv = e.Row.DataItem as DataRowView;
            this.Label1.Text = drv["col"].ToString();
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    protected void Page_Load(object sender, EventArgs e)

        if (!Page.IsPostBack)
            DataTable table = new DataTable();
            DataRow dr = table.NewRow();
            dr["col"] = "a";
            this.GridView1.DataSource = table;


    <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing">
                    <asp:Button ID="Button1" runat="server" CommandName="Edit" Text="edit" />
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
11/13/2008 8:57:50 AM

Similar Artilces:

Cannot implicitely convert type 'string' to 'System.Web.UI.WebControls.Label'
 I'm starting to make a website for users to login. Once they login, I'm showing their profile. So I populate some asp:label controls on Page_Load. My profile page (shown after the user logs in) contains: <%@ Page Language="C#" MasterPageFile="~/site.master" CodeFile="clientProfile.aspx.cs" Inherits="clientProfile" AutoEventWireup="true" Title="Car Look - Your profile" %> <asp:Content ID="Content1" ContentPlaceHolderID="mainContent" Runat="Server"> <div> &l...

ASPNET2 HELP! CS0266: Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.FileUpload'.
Server Error in '/start-movieposters' Application. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0266: Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.FileUpload'. An explicit conversion exists (are you missing a cast?) Source Error: ...

Cannot implicitly convert type 'System.Web.UI.WebControls.Label' to 'string' #2
Hi i am getting the following error "Cannot implicitly convert type 'System.Web.UI.WebControls.Label' to 'string'", what am i doing wrong, my code looks like this;protected void lbtnSubmit_Click(object sender, EventArgs e) {foreach(DataGridItem dgi in dgAvailability.Items) {AvailabilityBLC availabilityBLC = new AvailabilityBLC(); availabilityBLC.Availability.AvailabilityDay =(Label)dgi.FindControl("lblDay");availabilityBLC.Availability.AvailabilityPrice = (TextBox)dgi.FindControl("priceTxt"); availabilityBLC.Availability.BBooked = (CheckBox)dgi.FindControl("bookedChkBox"); try { availabilityBLC.AddAvailability(); }catch (Exception exception) { You have to use the text property to get the value: 1 availabilityBLC.Availability.AvailabilityDay =((Label)dgi.FindControl("lblDay")).Text; 2 availabilityBLC.Availability.AvailabilityPrice = ((TextBox)dgi.FindControl("priceTxt")).Text; 3 4 availabilityBLC.Availability.BBooked = ((CheckBox)dgi.FindControl("bookedChkBox")).Checked;  Please remember to click “Mark as Answer” so I know if my answer was good enough for you. Thanks. Hi thanks for responding, i get the following error on this line; "Error 1 Cannot implicitly convert type 'string' to 'float'  availabilityBLC.Availability.AvailabilityPrice = ((TextBox)dgi.FindControl("priceTxt")).Text; What can i do ...

Error: Cannot convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.ButtonField'
Hello, I am getting the following error during compiliation. Any suggestions to fix it. Thanks. Cannot convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.ButtonField' protected void gvEvents_RowCommand(Object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow selectedRow = gvEvents.Rows[index]; string sID; ButtonField btn; if (selectedRow.RowType == DataControlRowType.DataRow) { sID = ((ButtonField)selectedRow.FindControl("ID")).DataTextFi...

Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox'
I am attempting to "Update" a field in a Datagrid, but no matter what I do (Using either Label or Text Boxes)  I keep getting the same error: Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox' The Error is highlighted below in the Sub... <==THE FIELD THAT CALLS THE ERROR  Any help would be greatly appreciated !!! Thanks !!   The code is as follows... <table border=0 height=210 bordercolor=olive ><tr valign=top><td> <asp:datagrid id="FacilityDataGrid" runat="server" Font-Names="Arial" Font-Size="11px" HorizontalAlign="Left" ItemStyle-Font-Size="x-small" HeaderStyle-Font-Bold="True"HeaderStyle-Font-Size="x-small" AlternatingItemStyle-BackColor="#FFFFFF" Cellpadding="0" BorderWidth="0"AutoGenerateColumns="False" BorderStyle="None" GridLines="None" BorderColor="#404040" Width="75%"DataKeyField="FacilityID"OnUpdateCommand="MyDataGrid_UpdateCommand"OnCancelCommand="MyDataGrid_CancelCommand"OnEditCommand="DG_Combo_Edit"> <AlternatingItemStyle BackColor="#FFFFFF"></AlternatingItemStyle><ItemStyle Font-Size="X-Small"></ItemStyle><HeaderStyle Font-Size="X-Small" Font-Bold="True" ForeCo...

CS0029: Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.DropDownList'
I've got another error. Don't know where this is coming from. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0029: Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.DropDownList'Source Error: Line 1: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="

BC30311: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.Label'.
I have a pretty basic page that includes a listview.  (Note, this is my first time working with listview, so I may have some of the terminology wrong).  In my list view, I display all the important data for each record, and ask the user to provide a status for each record by including a radiobutton list with various responses.  At the bottom of the page is one submit button, and when the user clicks submit, I'm saving each records value based upon which response is selected in the radiobutton list. My saving of data is working,  but I'm getting an error when i try to display a confirmation message that includes a label with each records selected value from the radiobutton list.  Any idea what I'm doing wrong and why I can't grab the value selected and display it ??  I'm bolding the line that throws the error.. My Code Behind.. Protected Sub updateResponse()For Each Item As ListViewItem In lvAudits.ItemsDim rList As RadioButtonList = CType(Item.FindControl("rbAnswer"), RadioButtonList)Dim lblAnswer As Label = rList.SelectedValue.ToStringlblAnswer.Visible = True Dim tblAnswer As Table = CType(Item.FindControl("tblAnswerArea"), Table)tblAnswer.Visible = FalseDim conn As SqlConnectionDim comm As SqlCommandDim reader As SqlDataReaderDim connectionString As String = ConfigurationManager.ConnectionStrings("xxxxConnectionString").ConnectionStringconn = New SqlConnection(con...

Having an error: BC30311: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.Label'.
Error Message: Compiler Error Message: BC30311: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.Label'. Line 13: myGetRandom.RetrieveDetails(lblQuestion.text, lblAnswers.text, lblViewCount.text, lblLastUpdated.text) Sub Page_Load Dim myGetRandom as new GetRandom myGetRandom.RetrieveDetails(lblQuestion.text, lblAnswers.text, lblViewCount.text, lblLastUpdated.text) End Sub Code behind Sub RetrieveDetails(lblQuestion as label, _ lblAnswers as label, _ lblViewCount as label, _ lblLastUpdated as...

Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.
Hi,  I have a formview with a dropdownlist created dynamically. i want to determine whether the dropdownlist was clicked. the code is written in the FormView1_DataBound method. I get the following error in the line below that is in italics and underlined: Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.   Here is my code: ddl_iFullname = New DropDownList ddl_iFullname.ID = "ddl_iFullname" ddl_iFullname.DataSource = ObjectDataSource3 ddl_iFullname.DataTextField = "fullname" ddl_iFullname.DataValueField = "...

Value of type 'System.Web.UI.Control' cannot be converted to 'System.Web.SiteMap'.
 Hello,         I receive this error "System.Web.UI.Control' cannot be converted to 'System.Web.SiteMap" when I try to find the Sitemap control.  ...            <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />            <asp:ListView ID="ListView1" runat="server">            <LayoutTemplate>    ...

Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TextBox'
I have a new page (wireframe) based on the User_Create page in the Time Tracker starter kit.  I have no code in the code behind page.  What might be causing this error?  This newbie needs help. I had a TextBox control named "Title" which appearantly conflicted with the page title. thanks!!! ...

Cannot implicitly convert type 'Login' to 'System.Web.UI.WebControls.Login'
hello  i have got this error on this part of code :protected void Wizard1_NextButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e) {if (e.CurrentStepIndex == 0) {System.Web.UI.WebControls.Login l = (Login)Wizard1.FindControl("Login1");if (Membership.ValidateUser(l.UserName, l.Password)) { FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMeSet);e.Cancel = false; } else {l.InstructionText = "Your login attempt was not successful. Please try again."; l.InstructionTextStyle.ForeColor = System.Drawing.Color.Red;e.Cancel = true; } } else {if (!User.Identity.IsAuthenticated) {e.Cancel = true; Wizard1.ActiveStepIndex = 0; } } }   any ideas? thank you! Could try this: System.Web.UI.WebControls.Login l = (System.Web.UI.WebControls.Login)Wizard1.FindControl("Login1") as System.Web.UI.WebControls.Login;  See if that works. If that works just add a 'using System.Web.UI.WebControls;' to the top of your code-behind page, and shorten System.Web.UI.WebControls.Login to Login. Sounds like it's either not casting right, or there is another class of Login and it's getting confused on whether you mean System.Web.UI.WebControls.Login or whether you mean 'Login' as specified in the (Login) prefixing the find control lookup. Let me know if that helps.______________________________________Robert Lindley | Sr. Software Engineer - MCP, MCADASTRA Innovations, Ltd. -...

Error: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.Label
Here is the code:Dim dato_start_2 as DateTime Dim varighet_str as string Dim dato_differanse as string dato_start_2 = tabell_2.Rows(DataGrid1.SelectedIndex).Item("dato_tid_sendt") dato_differanse = DateDiff(DateInterval.Day, dato_start_2, now) Label12 = "" & dato_differanse & ""  ........and theCompiler Error Message: BC30311: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.Label'.Why and how?RegardsLars/Norway To set a text for a Label you need to use its Text property, in your code you try to set the Label to a Text and that is the reason why you g...

Operator '&' is not defined for types 'String' and 'System.Web.UI.WebControls.TextBox'
Can anyone tell me what this error message means, and what to do to correct it.  Here is the code that has the error:  Dim sql As Stringsql = "INSERT INTO tblConnecting (Date, Member, Name, Company, Phone, Fax, Address, NamesofAttendees, PaymentType, Email) " _ & "Values('" & Today() & "', '" & blnMember & "', '" & Me.txtName.Text & "', '" & Me.txtCompany.Text & "', '" _& Me.txtPhone.Text & "', '" & Me.txtFax.Text &...

BC30311: Value of type 'Control' cannot be converted to 'System.Web.UI.WebControls.CheckBox'
 Hi, can somebody help me on this problem. It works at first, but all of a sudden, it fails, and I can't find out why.    1 Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) 2 3 If Not CheckRequiredField() Then 4 MessageBox("Please complete the input data!") 5 Exit Sub 6 End If 7 8 Dim nRow As Integer 9 Dim Ctrl As Control 10 Dim chkDelete As Object 11 Dim LookupID, Name, Desc, Type As String 12 13 nRow = 0 14 15 For Each Ctrl In phLookUp.Controls 16 17 If Ctrl.GetType() Is GetType(CheckBox) Then 18 19 ' Checked = Request.Form("chkDelete" & nRow) 20 LookupID = Request.Form("txtLookupID" & nRow) 21 Name = Request.Form("txtName" & nRow) 22 Desc = Request.Form("txtDesc" & nRow) 23 Type = Request.Form("txtType" & nRow) 24 25 If CType(Ctrl, CheckBox).Checked Then '--> This is the line that causes error 26 ' 27 'delete 28 strSQL = "DELETE esd_lookup " & _ 29 "WHERE lookup_id = " & LookupID 30 31 objAdapter ...

BC30311: Value of type 'System.Web.UI.WebControls.RadioButtonList' cannot be converted to 'String'.
I have a listview that I'm working with.  Each record returned by my sql query is displayed in my list view as text, with the exception of one field, which I need to display as a radiobutton list.  I tried to set the value of the radiobutton in my codebehind, but keep getting errors.  How do I tell this radiobutton list that the value that should be selected when the page loads is equal to the value returned from my sql query?    The line in bold throws the error... How am I supposed to indicate what value to have selected when the page loads? <asp:RadioButtonList ID="rbAnswer" runat="server"><asp:ListItem Text="Not Yet Answered" Value="Not Yet Answered" ></asp:ListItem><asp:ListItem Text="No Information" Value="No Information"></asp:ListItem><asp:ListItem Text="Yes, Will Reply Now" Value="Will Reply Now"></asp:ListItem><asp:ListItem Text="Yes, Will Send Later" Value="Will Send Later"></asp:ListItem></asp:RadioButtonList> Here's what I tried in my code behind.. For Each Item As ListViewItem In lvAudits.ItemsDim rb As RadioButtonList = CType(Item.FindControl("rbAnswer"), RadioButtonList)rb.SelectedValue = CType(Item.FindControl("rbAnswer"), RadioButtonList)NextNever make important decisions on a Monday! rb.SelectedValue = CType(Item.FindControl("rbAn...

BC30311: Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TextBox'.
 Hello everyone, I receive the error in the subject when viewing this page, I can get it to work fine without the master page and only the textboxes, but that causes an error with line 11, even when the page contents do process to the form. I don`t understand the error and I would appreciate any guidance on this. Thanks for reading.1 <%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %> 2 3 <script runat="server"> 4 5 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 6 Dim D...

Hi Friends, I am trying to limit the width of ImageButton control not to exceed 120 pixels. But neither of the code snippets below work. Any suggestions? // ------------------------ int iWidth = 120; if (this.ImageButton1.Width > Unit.Parse(iWidth.ToString())) { this.ImageButton1.Width = 120; } // ------------------------ if (this.ImageButton1.Width > 120) { this.ImageButton1.Width = 120; } // ------------------------ Thank you in advance for your feedback. Rajan this.ImageButton1.Width is of datatype "unit" where a...

'System.Web.UI.Control' cannot be converted to 'String'.
I am trying to run a simple Edit, Update, Delete. I found a simple example in a book I've got. My only concern is withing the string it's first Declaration is Read only, so it won't be edited. and for some reason I am getting this error: The update function that is right after the page_load is giving me the problems. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30311: Value of type 'System.Web.UI.Control' cannot be converted to 'String'. Source Error: Line 108: Line 109: 'Userid.Text= e.Item.Cells(1).Text Line 110: Dim UserID as String = e.Item.Cells(1).Controls(0) Line 111: Line 112: 'Reference each TexBox Sub Page_Load(send as Object, e as EventArgs) If Not Page.IsPostBack then dgCustomers.DataSource = GetCustomers() dgCustomers.DataBind() End If End Sub Sub dgCustomers_Update(send as Object, e as DataGridCommandEventArgs) 'Determine the value of the UserID Coumn 'Dim UserID as String 'Userid.Text= e.Item.Cells(1).Text Dim UserID as String = e.Item.Cells(1).Controls(0) 'Reference each TexBox Dim FirstNameTextBox as TextBox = e.Item.Cells(2).Controls(0) Dim LastNameText...

BC30452: Operator '&' is not defined for types 'String' and 'System.Web.UI.WebControls.AccessDataSource'.
hi everyone, i keep getting the error page... Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30452: Operator '&' is not defined for types 'String' and 'System.Web.UI.WebControls.AccessDataSource'. Source Error:   Line 20: Line 21: cmdSelect = New Data.OleDb.OleDbCommand(strSelect, conMaterials)Line 22: cmdSelect.Parameters.Add("@grad_attribute_name", "%" & gradatt_search & "%")Line 23: cmdSelect.Parameters.Add("@grad_element_name", "%" & gradele_search & "%")Line 24: cmdSelect.Parameters.Add("@discipline_name", "%" & discipline_search & "%")  ive search around the net but cant find any answers. im a relative newbie to asp and ado and really don't even know what the msg is telling is the rest of my code if it helps.<%@Import Namespace = "System.Data.OleDb" %><script runat="server">    Protected Sub Button1_Click(ByVal sender As Object, ByV...

Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'.
I'm getting this error on a page the needs to execute two separate stored procedures.  The first one, is the main insert, and returns the identity value for the ClientID.  The second stored procedure inserts data, but needs to insert the ClientID returned in the first stored procedure.  What am I doing wrong with including the identity value "ClientID" in the second stored procedure?  Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'. Description: An unhandled exception occurred during t...

Error Serializing Value 'System.Web.UI.WebCOntrols.TreeNode' of type 'System.Web.UI.WebCOntrols.TreeNode'
Hi, I am  getting the error stated in the subject when i am storing a TreeNode in a ViewState and then using it as follows if (ViewState["ProductCounty"]!=null) { TreeNode _productCountyNode = DataTree.FindNode(((TreeNode)ViewState["ProductCounty"]).ValuePath); _productCountyNode.Expand(); } what could be causing this error? Hi, I believe TreeNode isn't serializable in a way its required for objects which can be put to ViewState - as reference - (TreeNode implements IStateManager and is meant to work together with TreeView itself saving it...

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.
Hi, any idea why I'm getting the following error?Line 45: protected void CartGrid_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e) Line 46: { Line 47: TextBox QuantityTextBox = (TextBox)CartGrid.Rows[e.RowIndex].Cells[2].Controls[0]; Line 48: int Quantity = Convert.ToInt32(QuantityTextBox.Text); Line 49: Are you sure that the control at CartGrid.Rows[e.RowIndex].Cells[2].Controls[0] isn't a LiteralControl?  How are you creating code this in your code?Brent JenkinsASP.NET, C#, Web  ...

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'
Hello, Goal: enter a number in two fields HoursPerUnit and PeoplePerUnit and the value for the third field, TotalHoursPerUnit will populate after the the number in the two fields have been caculated.  Using the code below I receive the error message above.  Please tell me what am I doing wrong? Do I need to cast the text as a literal?  Please help? Thank you in advance, <%@ Page Language="VB" MasterPageFile="Default.master" AutoEventWireup="false" CodeFile="frmHR.aspx.vb" Inherits="frmHR" title="HR" %><asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">    HR<br /><script language =javascript  type="text/javascript">function Calculate(HoursPerUnit, PeoplePerUnit, TotalHoursPerUnit){    TotalHoursPerUnit.value = HoursPerUnit.value * PeoplePerUnit.value;}   </script>    <br />    <asp:LinkButton ID="CheckAll" runat="server">Check All</asp:LinkButton>    <asp:LinkButton ID="UncheckAll" runat="server">Uncheck All</asp:LinkButton><br />    &nbsp;<br />    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="HR...

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

Resources last updated: 3/25/2016 9:06:46 AM