Garrett Pe
Garrett Pe

Reputation: 31

‘label’ does not contain a definition for ‘Name’ and no extension method

I am getting this error message on the code below:

‘label’ does not contain a definition for ‘Name’ and no extension method ‘Name’ accepting a first argument type of label could be found. (are you missing or using directive or an assembly reference?)

It is in regards to lbl.Name and lbl.Location but I have no idea why.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace budgetTracker
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        static int i = 1;

        protected void saveSalaryButton_Click(object sender, EventArgs e)
        {
            monthlySalaryLabel.Text = "$" + salaryInput.Text;
        }

        private void addExpense()
        {
            Label lbl = new Label();
            lbl.Name = "expense" + i.ToString();
            lbl.Text = expenseNameInput.Text;
            lbl.Location = new Point(15, 15);
            this.Controls.Add(lbl);
            expenseNameInput.Text = String.Empty;
        }

        protected void addExpenseButton_Click(object sender, EventArgs e)
        {
            addExpense();
        }
    }
}

Upvotes: 0

Views: 2744

Answers (2)

Naveen
Naveen

Reputation: 294

In label class there is no property called Name

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

That asp:Label belongs to the name space System.Web.UI.WebControls, in that class there is no property called Name. For uniquely identify that control you should use ID instead for Name, So the code will be:

Label lbl = new Label();
lbl.ID= "expense" + i.ToString(); // Change is here
lbl.Text = expenseNameInput.Text;  
this.Controls.Add(lbl);

For fixing the location of the control in the container, I think the better option for you is to use styling. Try something like this:

lbl.Style.Add("width","40px");
lbl.Style.Add("top", "10px");

Upvotes: 2

Related Questions