5

In .aspx I have

<body>
  <form id="form2" runat="server">
 <asp:GridView ID="GridView" runat="server" AutoGenerateColumns="True" Width="100%" ViewStateMode="Enabled">
 <Columns>
    <asp:BoundField ItemStyle-Width="150px" DataField="id" HeaderText="iD" />
    <asp:BoundField ItemStyle-Width="150px" DataField="nme" HeaderText="Name" />
    </Columns>
</asp:GridView>
   </form>
</body>

In .cs I have

private void Grid()
{
    string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT id, nme FROM mytable"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView.DataSource = dt; //error occurs here
                    GridView.DataBind();
                }
            }
        }
    }
}

I receive the error CS0120 An object reference is required for the non-static field, method, or property 'BaseDataBoundControl.DataSource'

The .cs does not seem to recognize the GridView from the .aspx page. using .net 4.6.1

1
  • 1
    You forgot to put the data type in 'using (dt = new DataTable())' Commented Sep 7, 2019 at 15:30

1 Answer 1

5

Don't call your GridView "GridView". The framework doesn't know whether you're talking about your instance of the GridView or whether you're talking about the class GridView. That's confusing to discuss, and it's confusing for the compiler. Change the ID to something else that doesn't conflict with a pre-existing type name, and update your code behind appropriately. You usually name it after what it contains, ex CustomersGridView.

Markup

<asp:GridView ID="CustomersGridView" runat="server">

Code behind

CustomersGridView.DataSource = dt;
CustomersGridView.DataBind();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.