2017-01-05 1 views
0

Я новичок в C#. Просто следуйте простым примерам из уроков Кудвенката. http://csharp-video-tutorials.blogspot.com/2012/10/calling-stored-procedure-with-output.htmlWebForm1 не содержит определения для «Контекст»

Продолжайте получать эти ошибки и не можете понять, что я делаю неправильно?

Моего .aspx файл:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="WebForm1"%> 

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <table style="border: 1px solid black; font-family:Arial"> 
      <tr> 
       <td> 
        Employee Name 
       </td> 
       <td> 
        <asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox> 
       </td> 
      </tr>   
      <tr> 
       <td> 
        Gender 
       </td> 
       <td> 
       <asp:DropDownList ID="ddlGender" runat="server"> 
        <asp:ListItem>Male</asp:ListItem> 
        <asp:ListItem>Female</asp:ListItem> 
       </asp:DropDownList> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        Salary 
       </td> 
       <td> 
        <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox> 
       </td> 
      </tr>  
      <tr> 
       <td colspan="2"> 
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> 
       </td> 
      </tr>   
      <tr> 
       <td colspan="2"> 
        <asp:Label ID="lblMessage" runat="server"></asp:Label> 
       </td> 
      </tr> 
     </table> 
    </form> 
</body> 
</html> 

В моем aspx.cs файл txtEmployeeName.Text, ddlGender.SelectedValue и 'txtSalary.Text' имеет красное подчеркивание, что говорит "The name .txt does not exist in a current context"

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Configuration; 


namespace adoDemo 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     protected void btnSubmit_Click(object sender, EventArgs e) 

     { 
      //Read the connection string from Web.Config file 
      string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(ConnectionString)) 
      { 
       //Create the SqlCommand object 
       SqlCommand cmd = new SqlCommand("spAddEmployee", con); 
       //Specify that the SqlCommand is a stored procedure 
       cmd.CommandType = System.Data.CommandType.StoredProcedure; 

       //Add the input parameters to the command object 
       cmd.Parameters.AddWithValue("@Name", txtEmployeeName.Text); 
       cmd.Parameters.AddWithValue("@Gender", ddlGender.SelectedValue); 
       cmd.Parameters.AddWithValue("@Salary", txtSalary.Text); 

       //Add the output parameter to the command object 
       SqlParameter outPutParameter = new SqlParameter(); 
       outPutParameter.ParameterName = "@EmployeeId"; 
       outPutParameter.SqlDbType = System.Data.SqlDbType.Int; 
       outPutParameter.Direction = System.Data.ParameterDirection.Output; 
       cmd.Parameters.Add(outPutParameter); 

       //Open the connection and execute the query 
       con.Open(); 
       cmd.ExecuteNonQuery(); 

       //Retrieve the value of the output parameter 
       string EmployeeId = outPutParameter.Value.ToString(); 
       lblMessage.Text = "Employee Id = " + EmployeeId; 
      } 
     } 
    } 
} 

И мой aspx.designer. cs file:

//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated by a tool. 
// 
//  Changes to this file may cause incorrect behavior and will be lost if 
//  the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace adoDemo { 


    public partial class WebForm1 { 

     /// <summary> 
     /// form1 control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.HtmlControls.HtmlForm form1; 

     /// <summary> 
     /// txtEmployeeName control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.WebControls.TextBox txtEmployeeName; 

     /// <summary> 
     /// ddlGender control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.WebControls.DropDownList ddlGender; 

     /// <summary> 
     /// txtSalary control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.WebControls.TextBox txtSalary; 

     /// <summary> 
     /// btnSubmit control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.WebControls.Button btnSubmit; 

     /// <summary> 
     /// lblMessage control. 
     /// </summary> 
     /// <remarks> 
     /// Auto-generated field. 
     /// To modify move field declaration from designer file to code-behind file. 
     /// </remarks> 
     protected global::System.Web.UI.WebControls.Label lblMessage; 
    } 
} 
+0

Проверьте файл дизайнера, чтобы увидеть, если свойства были сгенерированный, если не удалить и воссоздать это текстовое поле – meda

+0

Я добавил файл конструктора. Извините, но как я могу узнать, были ли созданы свойства? – Oleg

+0

На самом деле там, просто воссоздайте его, а затем повторите попытку – meda

ответ

1

Вы можете получить эту ошибку из-за и asse mbly caching, потому что VS путается о том, что на самом деле нужно перекомпилировать. Просто delete the cache items и перекомпилируйте нормально.

Загляните в файл конструктора и посмотрите, создала ли Visual Studio запись для элементов управления. Убедитесь, что у вас нет другого файла с похожими объявлениями.

Много раз, лучший способ исправить это - удалить, воссоздать и переименовать форму. Поскольку мы не должны сами редактировать файл дизайнера.

+0

Я воссоздал и переименовал форму. Я также очистил каталог кэша VS. Но это все еще подчеркнуто: txtEmployeeName.Text, ddlGender.SelectedValue и 'txtSalary.Text' имеют красную подчеркивание, в которой говорится: «Имя .txt не существует в текущем контексте». Я начинаю ненавидеть этот язык :) – Oleg

+0

Большое спасибо. Мне помогло полностью удалить и воссоздать весь проект и переименовать все возможные файлы. Большое спасибо !!! – Oleg

0

Проблема заключается в этой строке

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="WebForm1"%> 

Это должно быть

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="adoDemo.WebForm1"%> 

Inherits должен также содержать имя namespace, в вашем случае adoDemo

Смежные вопросы