簡體   English   中英

當前上下文中不存在“名稱”

[英]The 'name' doesn't exist in the current context

我正在使用C#,ASP.NET網站,但遇到了問題。 它還將SQL數據庫用於插入目的。 我遇到的是,當我嘗試使用“ here here”在aspx文件中或在“ page.aspx.cs”背后的代碼中編寫代碼時,我仍然遇到相同的問題。

因此,我已經創建了一個作為“ Web窗體”的項目,它包括“注冊/身份”模塊,並且我正在“ Register.aspx”頁面上添加我需要的其他字段,然后單擊注冊,我正在嘗試將它們插入其他數據庫。

<script runat="server">
 protected void Unnamed20_Click(object sender, EventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["Users"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        string sql;
        sql = "insert users (username, title, gname, sname, dob, address, suburb, state, postcode, phone, email) values (@Username, @Title, @Gname, @Sname, @Dob, @Address, @Suburb, @State, @Postcode, @Phone, @Email)";
        SqlCommand cmd = new SqlCommand(sql, con);

        cmd.Prepare();

        String suburb = txtSuburb.Text;


        cmd.Parameters.AddWithValue("@Username", RegisterUser.UserName);
        cmd.Parameters.AddWithValue("@Title", txtTitle.Text);

    }

現在問題出現了,它說“ @Title”,txtTitle.Text是“ txtTitle.Text”,所以對我來說,它在我的網頁中稱為txtTitle.Text,但是當我嘗試通過上面的代碼訪問它時給我這個職位的錯誤。 它用紅色下划線標出,我不知道該如何解決。

這是txtTitle控件的標記:

<li>
    <asp:Label runat="server" AssociatedControlID="Title">Title</asp:Label>
    <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtTitle" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</li>

如何解決此問題,以便能夠通過代碼訪問這些控件?

如注釋所示, txtTitle控件位於向導控件內。 此類控件無法直接訪問,因此您需要使用FindControl

TextBox txtTitle = (TextBox)WizardControlIdHere.StepNameHere
                                               .ContentTemplateContainer
                                               .FindControl("txtTitle");
cmd.Parameters.AddWithValue("@Title", txtTitle.Text);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM