Mistr Mowgli Mistr Mowgli - 1 month ago 20
C# Question

How to Bind DataGridView with SqlDataReader

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.

enter image description here