How to Bind DataGridView with SqlDataReader

Mistr Mowgli picture Mistr Mowgli · Nov 7, 2016 · Viewed 14.1k times · Source

Can anyone help me in this Code Please. I am trying to bind data with datagridview. Query is returning values in sql server. But it's not binding any value in DataGridView....

     private void CheckMembers()
     {
        try
        {
            string query = "Select id, id-no, status From Members Where Head=@Head";

            sqlCommand = new SqlCommand(query, sqlConnection);
            sqlConnection.Open();
            sqlCommand.Parameters.AddWithValue("@Head", "2288885858");
            sqlDataReader = sqlCommand.ExecuteReader();

            if (sqlDataReader.HasRows)
            {
                fmGview.Visible = true;
                DataTable dt = new DataTable();
                dt.Load(sqlDataReader);
                MessageBox.Show(dt.ToString());
                fmGview.DataSource = dt;
            }
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString(), "Exception in CheckMembers");
        }
        finally
        {
            CheckConnectionStatus();
        }
   }

enter image description here

Answer

Set DataPropertyName for each column in the Columns designer. You do this by putting the mouse pointer over the right hand cell in the DataPropertyName row, where it says (none), and clicking the left mouse button. Select the text that says "(none)", and type the database field name that you want to be displayed in that DataGridView column.