C# code:
command = new SqlCommand(null, connection);
command = createSQLQuery(command); // returns a valid SQL Query that returns results in SQL Management Studio 2012
//dataGridView1.DataSource = GetData(command);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
connection.Close();
dataGridView1.DataSource = GetData(command);
debugMySQL();
public DataTable GetData(SqlCommand cmd) {
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
I am using C# with WinForm and developing with Visual Studio 2012.
Your question is rather vague, but I’ll try to answer as best as I could.
I think, normally, you need to define the type of command that you are going to pass into the
SqlCommand, before executing that command.command.Commandtype = CommandType.StoredProcedure;(OR)
command.CommandText = CommandType.Text;You can set the SQL query in string value after that.
command.CommandText = ""; // your SQL query, or the name of the stored procedure
Also, you don’t need to set the
DataSourceof the grid twice. You only need to set it after you got the result of you SQL query execution is returned.However you receive the result is your choice. But, you seemed to executed the command twice, with both
GetData()method andcommand.ExecuteReader()method. And also, you are setting theDataSourceof your grid twice too.I think even if you managed to set up the command object properly, because of your double executions, data might be lost somehow between them.
And, by the way, what data type is returned from the
createSQLQuery()method. You said it returned a valid SQL Query, but is it returned a valid sql query value instring, or your custom command object to parse into theSqlCommand?I’ll include the best operable procedure I know for reading from the SQL database and bind that data into the grid control.
I recommend you to receive the result as
DataTablerather thanSqlDataReader. CauseDataTableis more flexible and versatile.