0

I have a simple ASP.NET web app with a master and default page. I'm retrieving a row from the database using a stored procedure and ADO.net and binding it to a gridview but getting "Object reference not set to an instance of an object".

It's failing here: gvCategoryLevel1Names.DataSource = rdr;

Note: 1.) The 1st image, it states the gridview is null. Why?

2.) The last image. My gridview does not appear in the form in design mode. I believe it should.

Any ideas?

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Part145._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div>
       <h1>Implementing an autocomplete textbox in asp.net web forms.</h1>
       <h2>I am using a .asmx web service.</h2>
    </div> 

    <br />

    <asp:FormView ID="FormView1" runat="server">
        <ItemTemplate>
            <div style="font-family:Arial">
                <asp:TextBox ID="txtCategoryLevel1Name" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        
                <br />

                <asp:GridView ID="gvCategoryLevel1Names" runat="server" AutoGenerateColumns="False" GridLines="Both" CellPadding="10" Width="500" BorderColor="#efeeef" BorderWidth="33">
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText=" ID" />        
                        <asp:BoundField DataField="CategoryId" HeaderText=" Category Id" /> 
                        <asp:BoundField DataField="Name" HeaderText=" Name " />        
                    </Columns>  
                </asp:GridView>
            </div>
        </ItemTemplate>
    </asp:FormView>
   
    <script type="text/javascript">
        $(function () {
            $('#<%=txtCategoryLevel1Name%>').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "CategoryLevel1Service.asmx/GetCategoryLevel1Names",
                        data: "{ 'searchTerm': '" + request.term + "' }",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        success: function (data)
                        {
                            response(data.d);
                        },
                        error: function (result)
                        {
                            alert('There is a problem processing your request.');
                        }
                    });
                },
                minLength: 0
            });
        });
    </script>
</asp:Content>
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Part145
{
public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetGetCategoryLevel1("Luxury");
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        GetGetCategoryLevel1(txtCategoryLevel1Name.Text);
    }

    private void GetGetCategoryLevel1(string name)
    {

        string cs = ConfigurationManager.ConnectionStrings["MediaTreeview"].ConnectionString;

        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("dbo.Part145SelectCategoryLevel1", con);
            cmd.Parameters.Clear();

            cmd.CommandType = CommandType.StoredProcedure;

            if (!string.IsNullOrEmpty(name))
            {
                SqlParameter parameter = new SqlParameter("@Name", name);
                cmd.Parameters.Add(parameter);
            }

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

                // Set the reader.
                SqlDataReader rdr = cmd.ExecuteReader();

                if (rdr.HasRows == true)
                {
                    // Bind to the gridview.
                    gvCategoryLevel1Names.DataSource = rdr;
                    gvCategoryLevel1Names.DataBind();
                }
            }
            catch (SqlException sqlex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

}

enter image description here

enter image description here

enter image description here

enter image description here

user3020047
  • 868
  • 1
  • 15
  • 45
  • the gridview is a child of the formview so it won't be directly accessible. You have to use FindControl within the FormView to locate it – ADyson Jan 05 '18 at 14:17
  • I added this and got the same result. GridView gv = new GridView(); gv = (GridView)FormView1.FindControl("gvCategoryLevel1Names"); gv.DataSource = rdr; gv.DataBind(); – user3020047 Jan 05 '18 at 14:27
  • have you databound your formview before doing this? I can't see anything in your code which would bind the formview. And you might be best to do this action within the FormView's OnDataBound event, to be sure. See https://stackoverflow.com/questions/5900197/asp-net-access-control-in-formview-itemtemplate or https://stackoverflow.com/questions/6105634/cant-find-control-in-formview, or many others when you google this issue. – ADyson Jan 05 '18 at 14:46
  • Actually though, are you sure you even need a FormView? It doesn't seem to be of much benefit to your use case. – ADyson Jan 05 '18 at 14:50
  • I'm just trying to follow a tutorial and it defines the gridview in a formview. However, it seems to be an older version of .Net where as I am using version 4.5 and it creates a master page. http://csharp-video-tutorials.blogspot.com/2013/09/part-145-implementing-autocomplete.html – user3020047 Jan 05 '18 at 15:48
  • ??? From that link: `

    ` ...show me where the FormView is in that?
    – ADyson Jan 05 '18 at 15:49
  • The .NET version is almost certainly not relevant, everything you're doing has been supported since 2.0 at least, but the master page part is. You will already have a `
    ` tag (as is required ) in your masterpage. In ASP.NET forms, you don't need, and can't have, any further form tags in your application. Did you try to swap `
    ` with `
    – ADyson Jan 05 '18 at 15:51
  • Yes..I converted that
    to a as I was getting an error: Validation HTML5: Element form must not be nested withing element form. I did not realize the message was generated due to the tag in the master. I changed it back and it now runs. Thanks so much!
    – user3020047 Jan 05 '18 at 16:32

0 Answers0