首页 文章

'label'不包含'Name'的定义,也没有扩展方法

提问于
浏览
0

我在下面的代码中收到此错误消息:

'label'不包含'Name'的定义,也没有扩展方法'Name'可以找到接受第一个参数类型的标签 . (您是丢失还是使用指令或汇编引用?)

这是关于 lbl.Namelbl.Location 但我不知道为什么 .

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();
        }
    }
}

2 回答

  • 0

    In label class there is no property called Name

  • 2

    asp:Label 属于名称空间 System.Web.UI.WebControls ,在该类中没有名为 Name 的属性 . 为了唯一地标识该控件,您应该使用 ID 代替Name,所以代码将是:

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

    为了修复控件在容器中的位置,我认为更好的选择是使用样式 . 尝试这样的事情:

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

相关问题