Tobias
Tobias

Reputation: 3

I have been following a tutorial on a snake game for C# but there is one part of the code that is not working and I am not sure why

I am recently getting back into coding. I have been working on this Snake Game program that i've been following a tutorial on. However, I am a tad confused as to why its saying "The name dataGridView1 does not exist in the current context. Basically what I am trying to do is display score history in my program through a database and I have followed everything exactly how it is on the tutorial, just cant seem to make it work though. Any help would be appreciated as I am a complete noob at this, thank you!

    private void UpdateScoreBoard()
    {
        //Get data from database and show in data grid view
        string query = "SELECT Date,Name,Scores FROM scores";

        using(SqlConnection con = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(query, con);

            var ds = new DataSet();
            adapter.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];

            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
        }
    }
}

}

Upvotes: 0

Views: 116

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

You need to declare it in your Form object to be accessible (check the example here):

public class Form1 : System.Windows.Forms.Form
{
    // Declare the gridview as a class member.
    DataGridView dataGridView1 = new DataGridView();

    // Rest of the code

    private void UpdateScoreBoard()
    {
        //Get data from database and show in data grid view
        string query = "SELECT Date,Name,Scores FROM scores";

        using(SqlConnection con = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(query, con);

            var ds = new DataSet();
            adapter.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];

            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
        }
    }
}

Then at some point you need to add it to the form

this.Controls.Add(songsDataGridView);

Upvotes: 1

Related Questions