I have a winform app connected to access database as data source ,
but in access i was using this below SQL to generate a query table called trend:
TRANSFORM Count(Complaint_Number) AS [Total Numbers]
SELECT Nature_of_problem, Count(Complaint_Number) AS [Total Numbers of Issues]
FROM master_table
GROUP BY Nature_of_problem
PIVOT Format(Complaint_Received_On,"mmm") In ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
But i do not know how execute this & populate the same in datagrid box on form load event(dataset:CSCdataset) , please help me.
Advertisement
Answer
I guess you can find more information on your question here: How to query MS Access database with C# application? This post refers to the documentation: https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms971485(v=msdn.10)?redirectedfrom=MSDN
In my winform-app, I use an SQL Server. It is probably somehow the same procedure for an Access database:
using System.Data.SqlClient;
//open connection
//cnnString = $@"Data Source=<yourServer>;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=<yourDatabase>
SqlConnection cnn = new SqlConnection(@cnnString);
cnn.Open();
//execute query
string exec = $@"<your query>";
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(exec, cnn);
adapter.Fill(dataSet); //fill dataset
cnn.Dispose();
//read dataset
dataSet.Tables[0].Rows
You can enhance this code by putting cnn into a using statement, like so:
using (SqlConnection connection = new SqlConnection(
connectionString)) {
try {
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex){
//log and/or rethrow or ignore
}
}
Source: The C# using statement, SQL, and SqlConnection
To bind a DataTable to a DataGridView, just assign the DataTable to the DataSource Property of the DataGridView, like so:
dataGridView.DataSource = yourDataTable;
I hope I helped you a little with my answer. Cheers