当前上下文中不存在名称“txtname”

时间:2013-06-01 07:46:13

标签: c# visual-studio-2010

我正在使用visual studio 2010.当我运行asp页面时,它会显示错误"The name 'txtname' doest not exists in the current context"。我是C#编程需要帮助的新手。 我正在使用所有定义的变量,但我仍然感到困惑,为什么它会给出错误。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
namespace WebApplication1
{
    public partial class contactus : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //Create the msg object to be sent
                MailMessage msg = new MailMessage();
                //Add your email address to the recipients
                msg.To.Add("myinfo@yahoo.com");
                //Configure the address we are sending the mail from
                MailAddress address = new MailAddress("abc@gmail.com");
                msg.From = address;
                //Append their name in the beginning of the subject
                msg.Subject = txtName.Text + " :  " + txtName1.Text;
                msg.Body = txtMessage.Text;

                //Configure an SmtpClient to send the mail.
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true; //only enable this if your provider requires it
                //Setup credentials to login to our sender email address ("UserName", "Password")
                NetworkCredential credentials = new NetworkCredential("abc@gmail.com", "paswword");
                client.Credentials = credentials;

                //Send the msg
                client.Send(msg);

                //Display some feedback to the user to let them know it was sent
                lblResult.Text = "Your email has been received, you will be contacted soon by our representative if required.";

                //Clear the form
                txtName.Text = "";
                txtName1.Text = "";
                txtMessage.Text = "";
            }
            catch
            {
                //If the message failed at some point, let the user know
                lblResult.Text = "Your message failed to send, please try again.";
            }
        }

    }
}

3 个答案:

答案 0 :(得分:1)

当Code behind属性中的.cs文件名不匹配时,只会出现这种错误。

检查@Page directive上文件名和继承属性后面的代码,确保它们都匹配。

或者您似乎已经复制并粘贴了与之相关的控件或代码。

这通常会在designer文件中产生问题。

您可以删除该文本框,然后再次将其从toolbar

拖放到您的应用中

答案 1 :(得分:0)

如果它是常规html控件,则在txtName控件中添加runat="server"

答案 2 :(得分:0)

I know this is and old question. I got the same problem after copying few divs in a seperate place. This might be useful to anyone in future. Just remove runat="server" attribute of the relevenat tag and again insert it. It worked for me 100%.