The name does not exist in the current context

Hi!
Me again! Im sure this has been covered before but I can’t find a solution to my specific issue.

I had everything working until I tried to update my database, the code may not be correct but I kind of know what Im trying to do, if there is a better way but still using the format I have please tell me.

When I go to run my program I get the error “The name ‘loggedInAs’ does not exist in the current context” I get the same error for ‘bookingName’, ‘fromLocation’, ‘toLocation’, ‘dateLeaving’, ‘dateReturning’, ‘transport’, and ‘contactNumber’ within my update.aspx.cs.

I’m not sure whether its because my text boxes for editing are in the EditItemTemplate section or if its something else. I have put the EditItemTemplate section in Bold as this is where the error messages are being directed to.

Thanks for your help in advance,

Owain.

Here is my code below:

Update.aspx

<%@ Page Language=“C#” MasterPageFile=“~/TravelLog.master” AutoEventWireup=“true” CodeFile=“update.aspx.cs” Inherits=“update” Title=“Homepage” %>
<asp:Content ID=“Content1” ContentPlaceHolderID=“ContentPlaceHolder1” Runat=“Server”>
<h1>
Planned Journeys</h1>
<a name=“this”></a>
<asp:DataList id=“employeesList” runat=“server” BackColor=“#FFFFC0” Width=“800px” onItemCommand=“employeesList_ItemCommand”>

<HeaderTemplate>
<table width=“100%”>
<tr style=“background-color:#DFa894”>
<th>ID</th>
<th><a id=“A1” href=“Default.aspx#this” onserverclick=“SortName” runat=“server”>Name</a></th>
<th><a id=“A2” href=“Default.aspx#this” onserverclick=“SortFrom” runat=“server”>From</a></th>
<th><a id=“A3” href=“Default.aspx#this” onserverclick=“SortTo” runat=“server”>To</a></th>
<th><a id=“A4” href=“Default.aspx#this” onserverclick=“SortFromDate” runat=“server”>From Date</a></th>
<th><a id=“A5” href=“Default.aspx#this” onserverclick=“SortReturnDate” runat=“server”>Return Date</a></th>
<th><a id=“A6” href=“Default.aspx#this” onserverclick=“SortTransport” runat=“server”>Transport</a></th>
<th><a id=“A7” href=“Default.aspx#this” onserverclick=“SortContact” runat=“server”>Contact</a></th>
<th><a id=“A8”>Edit?</th>
</tr>

</HeaderTemplate>

  &lt;ItemTemplate&gt;
  &lt;asp:Literal ID="extraDetailsLiteral" runat="server" EnableViewState="false" /&gt;
  &lt;tr&gt;
  &lt;td&gt;&lt;%#Eval ("ID")%&gt;&lt;/td&gt;
    &lt;td&gt;&lt;%#Eval("bookingName")%&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval("from_loc") %&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval("to_loc") %&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval("dateLeaving") %&gt;&lt;/a&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval ("dateReturning") %&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval ("trans_type") %&gt;&lt;/td&gt;
  &lt;td&gt;&lt;%#Eval ("contactNumber") %&gt;&lt;/td&gt;
  &lt;td&gt;&lt;asp:LinkButton ID="editButton" runat="server" Text="Edit" CommandName="EditItem" /&gt;&lt;/td&gt;

  &lt;/tr&gt;

&lt;/ItemTemplate&gt;

[B] <EditItemTemplate>
<tr>
<td>
<asp:TextBox ID=“bookingName” runat=“server” Text=‘<%# DataBinder.Eval(Container.DataItem, “bookingName”) %>’ />
</td>
<td>
<asp:DropDownList ID=“DropDownList1” runat=“server” DataSourceID=“SqlDataSource1” DataTextField=“crtLocations” DataValueField=“crtLocations”></asp:DropDownList>
<asp:SqlDataSource ID=“SqlDataSource1” runat=“server” ConnectionString=“<%$ ConnectionStrings:TravelLogConn %>”
SelectCommand=“SELECT [crtLocations] FROM [locations]”></asp:SqlDataSource>
</td>
<td> <asp:DropDownList ID=“DropDownList2” runat=“server” DataSourceID=“SqlDataSource1” DataTextField=“crtLocations” DataValueField=“crtLocations”></asp:DropDownList>
<asp:SqlDataSource ID=“SqlDataSource2” runat=“server” ConnectionString=“<%$ ConnectionStrings:TravelLogConn %>”
SelectCommand=“SELECT [crtLocations] FROM [locations]”></asp:SqlDataSource>
</td>
<td>
<asp:TextBox ID=“contactNumber” runat=“server” Text=‘<%# DataBinder.Eval(Container.DataItem, “contactNumber”) %>’ />
</td>

</tr>

</EditItemTemplate>[/B]

&lt;FooterTemplate&gt;

 &lt;/table&gt;
&lt;br /&gt;
&lt;%# DataBinder.Eval(Container.DataItem, "bookingName") %&gt;
 &lt;asp:LinkButton ID="updateButton" runat="server" Text="Update" CommandName="UpdateItem" /&gt;

<asp:LinkButton ID=“button2” runat=“Server” Text=“Cancel” CommandName=“CancelEditing” />
</FooterTemplate>

</asp:DataList>

<asp:Label Text=“Sort Type:” runat=“server” ID=“Label1” />

<asp:DropDownList ID=“cboSortType” runat=“server”>
<asp:ListItem Value=“asc”>Ascending</asp:ListItem>
<asp:ListItem Value=“desc”>Descending</asp:ListItem>
</asp:DropDownList>

<asp:Label text=“Currently Sorted on:” ID=“lblStatus” runat=“server” />

<asp:Label ID=“dbErrorMessage” runat=“server” Text=“Label”></asp:Label>
</asp:Content>

update.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class update : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindList();
}
}
protected void BindList()
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;

    // Read the connection string from Web.config
    string connectionString =
        ConfigurationManager.ConnectionStrings[
        "TravelLogConn"].ConnectionString;
    // Initialize connection
    conn = new SqlConnection(connectionString);


    // Create command
    comm = new SqlCommand(
      "SELECT mainInfo.ID, mainInfo.loggedInAs, mainInfo.bookingName, mainInfo.dateLeaving, mainInfo.dateReturning, mainInfo.transport, mainInfo.contactNumber, fromLocation.crtLocations AS from_loc, toLocation.crtLocations AS to_loc, transport.transportType as trans_type FROM mainInfo INNER JOIN locations AS fromLocation ON fromLocation.locationID = mainInfo.fromLocation INNER JOIN locations AS toLocation ON toLocation.locationID = mainInfo.toLocation INNER JOIN transport AS transport ON transport.transportID = mainInfo.transport", conn);

    // Enclose database code in Try-Catch-Finally
    try
    {
        // Open the connection
        conn.Open();
        // Execute the command
        reader = comm.ExecuteReader();
        // Bind the reader to the DataList
        employeesList.DataSource = reader;
        employeesList.DataBind();
        // Close the reader
        reader.Close();

    }
    finally
    {
        // Close the connection
        conn.Close();

    }
}

public void SortName(object s, EventArgs e)
{
    SortDataList("bookingName " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on Name: " + cboSortType.SelectedItem.Text;
}

public void SortFrom(object s, EventArgs e)
{
    SortDataList("from_loc " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on To Location: " + cboSortType.SelectedItem.Text;
}

public void SortTo(object s, EventArgs e)
{
    SortDataList("to_loc " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on Date Leaving: " + cboSortType.SelectedItem.Text;
}

public void SortFromDate(object s, EventArgs e)
{
    SortDataList("dateLeaving " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on From Location: " + cboSortType.SelectedItem.Text;
}

public void SortReturnDate(object s, EventArgs e)
{
    SortDataList("dateReturning " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on Name: " + cboSortType.SelectedItem.Text;
}

public void SortTransport(object s, EventArgs e)
{
    SortDataList("trans_type " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on Name: " + cboSortType.SelectedItem.Text;
}

public void SortContact(object s, EventArgs e)
{
    SortDataList("contactNumber " + cboSortType.SelectedItem.Value);
    lblStatus.Text = "Currently Sorted on Name: " + cboSortType.SelectedItem.Text;
}


private void SortDataList(string strSort)
{
    SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["TravelLogConn"].ConnectionString);
    SqlDataAdapter objCmd = new SqlDataAdapter("SELECT mainInfo.ID, mainInfo.loggedInAs, mainInfo.bookingName, mainInfo.dateLeaving, mainInfo.dateReturning, mainInfo.transport, mainInfo.contactNumber, fromLocation.crtLocations AS from_loc, toLocation.crtLocations AS to_loc, transport.transportType as trans_type FROM mainInfo INNER JOIN locations AS fromLocation ON fromLocation.locationID = mainInfo.fromLocation INNER JOIN locations AS toLocation ON toLocation.locationID = mainInfo.toLocation INNER JOIN transport AS transport ON transport.transportID = mainInfo.transport", objConn);
    DataSet objDS = new DataSet();
    DataTable objDT = new DataTable();
    DataView objDV = new DataView();

    objCmd.Fill(objDS);
    objDT = objDS.Tables[0];
    objDV = objDS.Tables[0].DefaultView;

    objDV.Sort = strSort;

    employeesList.DataSource = objDV;
    employeesList.DataBind();
    objConn.Close();
}



protected void employeesList_ItemCommand(object source, DataListCommandEventArgs e)
{
    //Which button was clicked?
    if (e.CommandName == "EditItem")
    {
        employeesList.EditItemIndex = (int)e.Item.ItemIndex;
        BindList();
    }
    else if (e.CommandName == "CancelEditing")
    {
        employeesList.EditItemIndex = -1;
        BindList();
    }
    else if (e.CommandName == "UpdateItem")
    {

        // Define data objects
        SqlConnection conn;
        SqlCommand comm;

        // Read the connection string from Web.Config
        string connectionString = ConfigurationManager.ConnectionStrings["TravelLogConn"].ConnectionString;


        // Initialise connection
        conn = new SqlConnection(connectionString);


        // Create Command
        comm = new SqlCommand("UPDATE mainInfo bookingName = @bookingName, fromLocation = @fromLocation, toLocation = @toLocation WHERE ID = @ID ");
        // Add command parameters

        comm.Parameters.Add("@loggedInAs", System.Data.SqlDbType.NVarChar, 50);
        comm.Parameters["@loggedInAs"].Value = loggedInAs.Text;

        comm.Parameters.Add("@bookingName", System.Data.SqlDbType.NVarChar, 50);
        comm.Parameters["@bookingName"].Value = bookingName.Text;

        comm.Parameters.Add("@fromLocation", System.Data.SqlDbType.Int);
        comm.Parameters["@fromLocation"].Value = fromLocation.SelectedItem.Value;

        comm.Parameters.Add("@toLocation", System.Data.SqlDbType.Int);
        comm.Parameters["@toLocation"].Value = toLocation.SelectedItem.Value;

        SqlParameter parameterDate = new SqlParameter("@dateLeaving", SqlDbType.DateTime, 8);
        parameterDate.Value = dateLeaving.SelectedDate;
        comm.Parameters.Add(parameterDate);

        SqlParameter parameterDateR = new SqlParameter("@dateReturning", SqlDbType.DateTime, 8);
        parameterDateR.Value = dateReturning.SelectedDate;
        comm.Parameters.Add(parameterDateR);

        comm.Parameters.Add("@transport", System.Data.SqlDbType.Int);
        comm.Parameters["@transport"].Value = transport.SelectedItem.Value;


        comm.Parameters.Add("@contactNumber", System.Data.SqlDbType.NVarChar, 50);
        comm.Parameters["@contactNumber"].Value = contactNumber.Text;


        // Create command

        try
        {
            // Open the connection
            conn.Open();


            // Execute the command

            comm.ExecuteNonQuery();
            Response.Write("Testing");

            //Reload page if the query executed successfully
            Response.Redirect("add.aspx");
            dbErrorMessage.Text = "Journey saved";

        }
        catch (Exception g)
        {
            // Display error message
            dbErrorMessage.Text = "Error: " + g.Message;
        }
        finally
        {
            // Close the connection
            conn.Close();


        }




    }
  }
}

Its quite hard to decipher just looking at the plain text with out the fancy .NET formatting.

However the error should be simple enough to fix, it simply means at that point in your code behind, it cannot find the object your referencing. I can’t actually see the loggedInAs control?

Since the textboxes are inside the a template (in this case the EditTemplate) you need to use the FindControl method of the object e.Item to find it (e.Item is the template that contains the control).


TextBox loggedInAs = (TextBox)e.Item.FindControl("loggedInAs");

Cheers, I will give it a go on Monday when I get back to work :slight_smile:

O.