0

I have a blank DataGridView, with no rows or datasource set, I need to populate it using a select query (and hide some of the returned columns).

I have tried 3 different code methods, all of which don't error, they just do nothing. I can query the database and populate lists fine using the below connection string.

String connectionString = 
            "Data Source="     + Properties.Settings.Default.Sever    + ";" +
            "Initial Catalog=" + Properties.Settings.Default.Database + ";" +
            "Integrated Security=TRUE;";

1)

public void populateDataGrid1()
        {
            SqlConnection cnn = new SqlConnection(connectionString);

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.Connection = cnn;
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "SELECT 1,2,3,4 from X inner join Y where Z";
            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

            DataTable dtRecord = new DataTable();
            sqlDataAdap.Fill(dtRecord);
            dg_Data1.DataSource = dtRecord;
        }

2)

public void populateDataGrid2()
        {
            string select = "SELECT 1,2,3,4 from X inner join Y where Z";
            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = connectionString;
            SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn);

            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
            DataSet ds = new DataSet();
            dataAdapter.Fill(ds);
            dg_Data1.ReadOnly = true;
            dg_Data1.DataSource = ds;
        }

3)

string sql = "SELECT 1,2,3,4 from X inner join Y where Z";


            using (var connection = new SqlConnection(connectionString))
            using (var command = new SqlCommand(sql, connection))
            using (var adapter = new SqlDataAdapter(command))
            {
                connection.Open();
                var myTable = new DataTable();
                adapter.Fill(myTable);
                dg_Data1.DataSource = myTable;

            }
2
  • Have you checked the AutoGenerateColumns property of the DataGridView? If that's set to false somewhere, then new columns won't get added automatically. Also, have you checked to make sure your query returns anything? Commented Mar 21, 2016 at 15:54
  • @Tombala Ah this has fixed it, that property isn't displayed on the properties list for the grid, but manually setting it in code at Load has worked, thanks! Commented Mar 21, 2016 at 16:22

1 Answer 1

2

You need to set AutoGenerateColumns = true.

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.