The name TableGridView does not exist in the current context

I have been trying to make a grid with a variable data source in 'mvc',
so it will read data from diffent database tables.
The code I have so far comes from Asp.net prior to 'mvc' and am converting it.
I am now getting the following error:
The name TableGridView does not exist in the current context in line 83.
Thanks in advance for any help given.
below is the code I have in the view:
<li class="three">
        Grid-1:
        <asp:GridView ID="TableGridView" runat="server" AutoGenerateColumns="False">
        <Columns>
            
        </Columns>
        </asp:GridView>
        <li class="four">
        Grid-2:
        <%: Html.DisplayForModel("TableGridView")%>
        </li>

Open in new window

The code from the controller is blow: I have indicated line 83 where the error occures.
TableGridView.Columns.Add(BtnTmpField); // THIS IS LINE 83 WITH ERROR
[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection collection)
        {
            //string saveButton, string cancelButton
            if (collection["register"] != null)
            {
                string connString = "Data Source=" + Request.Form["server_tb"] + ";Initial Catalog=" + Request.Form["database_tb"]
                + ";Integrated Security=True; Connect Timeout=120" + ";";
                Session["ConnectionString"] = connString;
                Session["TableSelected"] = Request["table_tb"];
                Session["IsConnectionInfoSet"] = true;
                ViewBag.Message = "#" + Session["ConnectionString"] + "#";
                //TableGridView.DataSource = ds;
                //TableGridView.DataBind();
                CreateTemplatedGridView();
            }
            else if (collection["cancel"] != null)
            {
                ViewData["Message"] = "you wanna cancel";  // redirect to appropriate action
            }
            else
            {
                ViewData["Message"] = "what de hell are you trying to do?";  // redirect to appropriate action
            }
            return View();
        }
        void PopulateDataTable()
        {
            string tableName = (string)Session["TableSelected"];
            try
            {
                DataAccess da = new DataAccess();
                Table = da.GetData("Select * from " + tableName);
            }
            catch (Exception ex)
            {
                ViewData["Message"] =  ex.ToString();
                //MsgPanel.Visible = true;
            }
        }
        void CreateTemplatedGridView()
        {
            // fill the table which is to bound to the GridView
            PopulateDataTable();
            // add templated fields to the GridView
            TemplateField BtnTmpField = new TemplateField();
            BtnTmpField.ItemTemplate =
                new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.Item, "...", "Command");
            BtnTmpField.HeaderTemplate =
                new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.Header, "...", "Command");
            BtnTmpField.EditItemTemplate =
                new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.EditItem, "...", "Command");
            TableGridView.Columns.Add(BtnTmpField); // THIS IS LINE 83 WITH ERROR
            for (int i = 0; i < Table.Columns.Count; i++)
            {
                TemplateField ItemTmpField = new TemplateField();
                // create HeaderTemplate
                ItemTmpField.HeaderTemplate = new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.Header,
                                                              Table.Columns[i].ColumnName,
                                                              Table.Columns[i].DataType.Name);
                // create ItemTemplate
                ItemTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.Item,
                                                              Table.Columns[i].ColumnName,
                                                              Table.Columns[i].DataType.Name);
                //create EditItemTemplate
                ItemTmpField.EditItemTemplate = new DynamicallyTemplatedGridViewHandler(System.Web.UI.WebControls.ListItemType.EditItem,
                                                              Table.Columns[i].ColumnName,
                                                              Table.Columns[i].DataType.Name);
                // then add to the GridView
                TableGridView.Columns.Add(ItemTmpField);

            }
            // bind and display the data
            TableGridView.DataSource = Table;
            TableGridView.DataBind();
        }

Open in new window

homeshopperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bob LearnedCommented:
I don't understand what is different now.  Are you using Web Forms or Razor syntax with the view now?
0
homeshopperAuthor Commented:
Hi Bob,
The original project was aspx Web Forms.
First I am trying to convert to 'MVC' with aspx Engine.
Then once I get that to work, will convert to Razor syntax.
The problem at the moment is trying to find an alternative for:
(i.e bind the dataTable to a grid that works with 'mvc' etc)
All the examples I have seen so far, use a model or *.edm file.
I want controller & view code only, so that I can read all databases on the system.
Then selecting one will display it's tables etc.
The original web-forms code did this, but I know need an 'mvc' equivalent.
Thanks in advance for any help given.
TableGridView.DataSource = Table; & TableGridView.DataBind();
<asp:GridView ID="TableGridView" runat="server" AutoGenerateColumns="False">
        <Columns>
            
        </Columns>
        </asp:GridView>

Open in new window

0
homeshopperAuthor Commented:
Making some progress. In the controller I now have a dataTable.
In the view I now need code to display the data as a grid.
Any ideas? Thanks in advance for any help given.
The controller code is as below:
[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection collection)
        {
            //string saveButton, string cancelButton
            if (collection["register"] != null)
            {
                string connString = "Data Source=" + Request.Form["server_tb"] + ";Initial Catalog=" + Request.Form["database_tb"]
                + ";Integrated Security=True; Connect Timeout=120" + ";";
                Session["ConnectionString"] = connString;
                Session["TableSelected"] = Request["table_tb"];
                Session["IsConnectionInfoSet"] = true;
                ViewBag.Message = "#" + Session["ConnectionString"] + "#";
                string connectionstring = (string)Session["ConnectionString"];
                SqlConnection con = new SqlConnection(connectionstring);
                //open connection      
                con.Open();
                //create a data adapter and invoking the command.
                SqlDataAdapter ad = new SqlDataAdapter("select * from " + Session["TableSelected"], con);
                DataSet ds = new DataSet();
                ad.Fill(ds, "Emp");
                //Creating a Datatable object
                DataTable dt = new DataTable();
                dt = ds.Tables["Emp"];
                //  close the coonection
                con.Close();
                TableGridView = dt;
            }
            else if (collection["cancel"] != null)
            {
                ViewData["Message"] = "you wanna cancel";  // redirect to appropriate action
            }
            else
            {
                ViewData["Message"] = "what de hell are you trying to do?";  // redirect to appropriate action
            }
            return View(TableGridView);
        }

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

Bob LearnedCommented:
Since you can't use the GridView with Razor syntax, I would think that it would be better to find an MVC solution now, rather than later.

Grid.Mvc
https://gridmvc.codeplex.com/
0
homeshopperAuthor Commented:
Thanks for the link.
Yes, I'll consentrate on a razor solution.
I'll post new code later.
0
Bob LearnedCommented:
There is some overhead to a DataSet over a DataTable, so if you only need a DataTable, then I would that instead:

                DataTable dt = new DataTable("Emp");
                ad.Fill(dt);

Open in new window

0
homeshopperAuthor Commented:
I have managed to produce a grid from a dataTable now.
I have not tried using dataset yet.
The data is changed by selecting different tables with associated database from a textbox.
Do you know how I could now make the data editable?
Thanks in advance for the help.
The code I have so far is listed below:
Controller:
[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection collection)
        {
            //string saveButton, string cancelButton
            if (collection["register"] != null)
            {
                string connString = "Data Source=" + Request.Form["server_tb"] + ";Initial Catalog=" + Request.Form["database_tb"]
                + ";Integrated Security=True; Connect Timeout=120" + ";";
                Session["ConnectionString"] = connString;
                Session["TableSelected"] = Request["table_tb"];
                Session["IsConnectionInfoSet"] = true;
                string connectionstring = (string)Session["ConnectionString"];

                SqlConnection con = new SqlConnection(connectionstring);
                //open connection      
                con.Open();
                //create a data adapter and invoking the command.
                SqlDataAdapter ad = new SqlDataAdapter("select * from " + Session["TableSelected"], con);
                DataSet ds = new DataSet();
                ad.Fill(ds, "Emp");
                //Creating a Datatable object
                DataTable dt = new DataTable();
                dt = ds.Tables["Emp"];
                //  close the connection
                con.Close();
                //TableGridView = dt;
                ViewBag.Message = "#" + Session["ConnectionString"] + "#";
                return View(dt);
            }
            else if (collection["cancel"] != null)
            {
                ViewData["Message"] = "you wanna cancel";  // redirect to appropriate action
            }
            else
            {
                ViewData["Message"] = "what de hell are you trying to do?";  // redirect to appropriate action
            }
            return View();
        }

Open in new window

View:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <div>
    <h3>C.A.M.S.</h3>
    <ol class="round">
        <li class="one">
            <h5>Heading</h5>
        @Html.Label("Grids:", new { @style = "" })
        @Html.Label("Server:", new { @style = "z-index: 108; left: 232px;position: absolute; top: 23px" })
        @Html.TextBox("server_tb", ".\\", new { @Style = "z-index: 102; left: 282px; position: absolute;top: 22px; width: 123px;" })
        
        @Html.Label("User:", new { @style = "z-index: 104; left: 245px;position: absolute; top: 46px" })
        @Html.TextBox("user_tb", "sa", new { @Style = "z-index: 103; left: 282px; position: absolute;top: 45px;" })
        
        @Html.Label("Password:", new { @style = "z-index: 106; left: 214px;position: absolute; top: 70px" })   
        @Html.TextBox("pswrd_tb", "H6web97!", new { @Style = "z-index: 105; left: 282px; position: absolute;top: 69px;" })
        
        @Html.Label("Database:", new { @style = "z-index: 112; left: 212px;position: absolute; top: 93px" })
        @Html.TextBox("database_tb", "dBase", new { @Style = "z-index: 109; left: 282px; position: absolute;top: 92px;" })
        
        @Html.Label("Table:", new { @style = "z-index: 111; left: 238px;position: absolute; top: 117px" })
        @Html.TextBox("table_tb", "dBaseTable", new { @Style = "z-index: 110; left: 282px; position: absolute;top: 116px;" })
        
        <input type="submit" name="register" value="Register" style="z-index: 113;left: 282px; position: absolute; top: 143px"  />
        <input type="submit" name="cancel" value="Cancel" style="z-index: 114;left: 355px; position: absolute; top: 143px" />
        </li>
        <li class="two">
        Grid-1:
@if (Model != null)
{
        <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach (System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>
}
        </li>
        <li class="three">
        Grid-2:
        <!--
        
        -->
        <h6>Mess:@ViewData["Message"]</h6>
        </li>
    </ol>
</div>
}

Open in new window

0
Bob LearnedCommented:
You could have one view for display, and another for edit.  You can use Html.DisplayFor and Html.EditorFor extension methods to auto-generate the controls for the view.

Using Display Templates and Editor Templates in ASP.NET MVC
http://www.codeguru.com/csharp/.net/net_asp/mvc/using-display-templates-and-editor-templates-in-asp.net-mvc.htm
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
homeshopperAuthor Commented:
Thank you for the helpful link.
Tomorrow, I'll do some more experimenting.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.