Solved

The name 'tempDT' does not exist in the current context

Posted on 2009-07-01
7
559 Views
Last Modified: 2012-05-07
In the GridView1_SelectedIndexChanged method I'm getting 3 build errors saying that the name 'tempDT' does not exist.  Unable to fathom the reason for this, please advise.
PAGE CODE

==========

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <style type="text/css">

        .style1

        {

            width: 100%;

        }

        .style2

        {

            width: 549px;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:SqlDataSource ID="SqlCategoriesList" runat="server" 

            ConnectionString="<%$ ConnectionStrings:docstoresConnectionString %>" 

            

            SelectCommand="SELECT [Category] FROM [Category] WHERE ([Category] &lt;&gt; @Category) ORDER BY [Category]">

            <SelectParameters>

                <asp:Parameter DefaultValue="ALL ITEMS" Name="Category" Type="String" />

            </SelectParameters>

        </asp:SqlDataSource>

        <asp:SqlDataSource ID="SqlItemList" runat="server" 

            ConnectionString="<%$ ConnectionStrings:docstoresConnectionString %>" 

            onselecting="SqlItemList_Selecting" 

            SelectCommand="SELECT [Item_ID], [Item_Description], [Item_UnitofIssue], [Item_Image], [Item_ItemNo], [Item_MaxOrderQty] FROM [Items] WHERE (([Item_Active] = @Item_Active) AND ([Item_Category] = @Item_Category))">

            <SelectParameters>

                <asp:Parameter DefaultValue="true" Name="Item_Active" Type="Boolean" />

                <asp:ControlParameter ControlID="ddlCategory" Name="Item_Category" 

                    PropertyName="SelectedValue" Type="String" />

            </SelectParameters>

        </asp:SqlDataSource>

        <br />

        <table align="left" class="style1" cellspacing="15">

            <tr>

                <td bgcolor="#CCFF33" class="style2">

                    <asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" 

                        DataSourceID="SqlCategoriesList" DataTextField="Category" 

                        DataValueField="Category">

                    </asp:DropDownList>

                    - Select a category</td>

                <td bgcolor="#CCFF33">

                    Your order</td>

            </tr>

            <tr>

                <td class="style2">

                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 

                        DataKeyNames="Item_ID" DataSourceID="SqlItemList" 

                        EmptyDataText=".. Select a category"

                        OnSelectedIndexChanged="GridView1_SelectedIndexChanged"

                        OnSelectedIndexChanging="GridView1_SelectedIndexChanging">

                        <Columns>

                            <asp:CommandField ButtonType="Button" SelectText="Add" 

                                ShowSelectButton="True" />

                            <asp:TemplateField>

                                <ItemTemplate>

                                    <asp:TextBox ID="QtyToAdd" runat="server" Width="25px"></asp:TextBox>

                                </ItemTemplate>

                            </asp:TemplateField>

                             

                            <asp:BoundField DataField="Item_Description" HeaderText="Description" 

                                SortExpression="Item_Description" />

                            <asp:BoundField DataField="Item_UnitofIssue" HeaderText="Unit of Issue" 

                                SortExpression="Item_UnitofIssue" />

                            <asp:BoundField DataField="Item_Image" HeaderText="Image" 

                                SortExpression="Item_Image" />

                            <asp:BoundField DataField="Item_ItemNo" HeaderText="Item No" 

                                SortExpression="Item_ItemNo" />

                            <asp:BoundField DataField="Item_MaxOrderQty" HeaderText="Max Qty" 

                                SortExpression="Item_MaxOrderQty" />

                            <asp:TemplateField HeaderText="ID" Visible="False">

                                <ItemTemplate>

                                    <asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_ID") %>'></asp:Label>

                                </ItemTemplate>

                            </asp:TemplateField>

                        </Columns>

                    </asp:GridView>

                </td>

                <td valign="top">

                    <asp:GridView ID="ItemsInOrder" runat="server" 

                        EmptyDataText=".. No items in order">

                    </asp:GridView>

                    </td>

            </tr>

            <tr>

                <td class="style2">

                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label3" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label4" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label5" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label6" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label7" runat="server" Text=""></asp:Label><br />

                    <asp:Label ID="Label8" runat="server" Text=""></asp:Label>

                    <br />

                    <asp:Label ID="Label9" runat="server" Text=""></asp:Label> <br />

                    <asp:Label ID="Label10" runat="server" Text=""></asp:Label>

                    <br />

                </td>

                <td valign="top">

                    &nbsp;</td>

            </tr>

        </table>

    

    </div>

    </form>

</body>

</html>
 

CODE BEHIND

============

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;
 
 

public partial class _Default : System.Web.UI.Page

{

 
 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            CreateDataTable();
 

        }

    }
 
 

    private DataTable CreateDataTable()

    {

        DataTable tempDT = new DataTable();
 

        DataColumn myDataColumn;
 

        myDataColumn = new DataColumn();

        myDataColumn.DataType = Type.GetType("System.String");

        myDataColumn.ColumnName = "id";

        tempDT.Columns.Add(myDataColumn);
 

        myDataColumn = new DataColumn();

        myDataColumn.DataType = Type.GetType("System.String");

        myDataColumn.ColumnName = "qtyordered";

        tempDT.Columns.Add(myDataColumn);
 

        myDataColumn = new DataColumn();

        myDataColumn.DataType = Type.GetType("System.String");

        myDataColumn.ColumnName = "itemdesc";

        tempDT.Columns.Add(myDataColumn);
 

        myDataColumn = new DataColumn();

        myDataColumn.DataType = Type.GetType("System.String");

        myDataColumn.ColumnName = "unitofissue";

        tempDT.Columns.Add(myDataColumn);
 

        myDataColumn = new DataColumn();

        myDataColumn.DataType = Type.GetType("System.String");

        myDataColumn.ColumnName = "itemno";

        tempDT.Columns.Add(myDataColumn);
 

        return tempDT;

    }
 

    protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)

    {
 

        // Get the currently selected row using the SelectedRow property.

        GridViewRow row = GridView1.SelectedRow;
 

        // Get the invisible gridview column Item_ID value  

        string idText = ((Label)GridView1.SelectedRow.FindControl("lblItemID")).Text;
 

        // Get the value of the textbox qty template field

        string qtyText = ((TextBox)GridView1.SelectedRow.FindControl("QtyToAdd")).Text;

        

        // Display selected item back to the page

        Label1.Text = "Cell 0 = " + row.Cells[0].Text;

        Label2.Text = "Cell 1 = " + row.Cells[1].Text;

        Label3.Text = "Cell 2 = " + row.Cells[2].Text;

        Label4.Text = "Cell 3 = " + row.Cells[3].Text;

        Label5.Text = "Cell 4 = " + row.Cells[4].Text;

        Label6.Text = "Cell 5 = " + row.Cells[5].Text;

        Label7.Text = "Cell 6 = " + row.Cells[6].Text;

        Label8.Text = "Cell 7 = " + row.Cells[7].Text;

        Label9.Text = "Record ID = " + idText;

        Label10.Text = "Qty Ordered ID = " + qtyText;
 

        

        // Insert data into the temp datatable

        DataRow myNewRow;

        myNewRow = tempDT.NewRow();
 

        myNewRow["id"] = idText;

        myNewRow["qtyordered"] = qtyText;

        myNewRow["itemdesc"] = row.Cells[2].Text;

        myNewRow["unitofissue"] = row.Cells[3].Text;

        myNewRow["itemno"] = row.Cells[5].Text;
 

        tempDT.Rows.Add(myNewRow);
 

        // Bind the grid with the temp datatable

        ItemsInOrder.DataSource = tempDT;

        ItemsInOrder.DataBind();
 

    }
 

    protected void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)

    {

        GridViewRow row = GridView1.Rows[e.NewSelectedIndex];
 

    }
 

    protected void SqlItemList_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

    {
 

    }

}

Open in new window

0
Comment
Question by:chris_desborough
7 Comments
 
LVL 5

Expert Comment

by:aternex
ID: 24758529
As far as I can see the tempDT is private to the CreateDataTable method and would not exist in the GridView1_SelectedIndexChanged subroutine as it is not being called.
0
 
LVL 1

Author Comment

by:chris_desborough
ID: 24758614
Okay... fairly new to C#. How would you suggest I correct the problem?
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 24758899
Just part of your code with some modifications:
Just making tempDT accessible to entire class...
public partial class _Default : System.Web.UI.Page
{
      DataTable tempDT = null;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CreateDataTable();
         }
    }
 
 
    private DataTable CreateDataTable()
    {
        tempDT = new DataTable();
 
        DataColumn myDataColumn;
 
...Rest of code remains as it is...
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:chris_desborough
ID: 24758964
Now getting an another error in the GridView1_SelectedIndexChanged method on this line:

 myNewRow = tempDT.NewRow(); - Object reference not set to an instance of an object.





0
 
LVL 41

Accepted Solution

by:
guru_sami earned 200 total points
ID: 24759138
in that case may be you want to declare that static:  
static DataTable tempDT = null;

Or may be look into setting it as a property....
0
 
LVL 15

Expert Comment

by:jinal
ID: 24759158
Hi ,

As you said you are new to C# . As you are using ASP.net so each time you click ne request is processed. In order to keep track of older data you have to use state management of ASP.net.

Session.
ViewState.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CreateDataTable();

        }
    }


    private DataTable CreateDataTable()
    {
        DataTable tempDT = new DataTable();

        DataColumn myDataColumn;

        myDataColumn = new DataColumn();
        myDataColumn.DataType = Type.GetType("System.String");
        myDataColumn.ColumnName = "id";
        tempDT.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.DataType = Type.GetType("System.String");
        myDataColumn.ColumnName = "qtyordered";
        tempDT.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.DataType = Type.GetType("System.String");
        myDataColumn.ColumnName = "itemdesc";
        tempDT.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.DataType = Type.GetType("System.String");
        myDataColumn.ColumnName = "unitofissue";
        tempDT.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.DataType = Type.GetType("System.String");
        myDataColumn.ColumnName = "itemno";
        tempDT.Columns.Add(myDataColumn);

        ViewState["Data"] = tempDT;

        return tempDT;
    }

    protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
    {

        // Get the currently selected row using the SelectedRow property.
        GridViewRow row = GridView1.SelectedRow;

        // Get the invisible gridview column Item_ID value  
        string idText = ((Label)GridView1.SelectedRow.FindControl("lblItemID")).Text;

        // Get the value of the textbox qty template field
        string qtyText = ((TextBox)GridView1.SelectedRow.FindControl("QtyToAdd")).Text;

        // Display selected item back to the page
        Label1.Text = "Cell 0 = " + row.Cells[0].Text;
        Label2.Text = "Cell 1 = " + row.Cells[1].Text;
        Label3.Text = "Cell 2 = " + row.Cells[2].Text;
        Label4.Text = "Cell 3 = " + row.Cells[3].Text;
        Label5.Text = "Cell 4 = " + row.Cells[4].Text;
        Label6.Text = "Cell 5 = " + row.Cells[5].Text;
        Label7.Text = "Cell 6 = " + row.Cells[6].Text;
        Label8.Text = "Cell 7 = " + row.Cells[7].Text;
        Label9.Text = "Record ID = " + idText;
        Label10.Text = "Qty Ordered ID = " + qtyText;


        // Insert data into the temp datatable
        DataRow myNewRow;
        DataTable tempDT = (DataTable)ViewState["Data"];
        myNewRow = tempDT.NewRow();

        myNewRow["id"] = idText;
        myNewRow["qtyordered"] = qtyText;
        myNewRow["itemdesc"] = row.Cells[2].Text;
        myNewRow["unitofissue"] = row.Cells[3].Text;
        myNewRow["itemno"] = row.Cells[5].Text;

        tempDT.Rows.Add(myNewRow);
        ViewState["Data"] = tempDT;
        // Bind the grid with the temp datatable
        ItemsInOrder.DataSource = tempDT;
        ItemsInOrder.DataBind();

    }

    protected void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.NewSelectedIndex];

    }

    protected void SqlItemList_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

    }


0
 
LVL 1

Author Closing Comment

by:chris_desborough
ID: 31598971
Thanks sami, now working as expected. Setting it 'static' made the difference. Thanks to other contributors for their advice.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Scheduled IIS .Net2 AppPools recycle and SQL connection Hangs 33 93
Get id from json Data with NewtonSoft 3 35
Runtime Error 2 29
VB.Net How to Exit Sub - Exit Form??? 5 51
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now