Jevon Jevon - 2 months ago 10
SQL Question

datagrid view on a newly added sql table

I've looked and done my research on datagrid view and I have seen the way of using the wizard or coding it manually. But am wondering if there is any way to do it on a newly added table. Eg. I have a function that creates and then outputs a csv file to that newly created table in MSSQL and that same table that has been created. I would want to view its contents in a datagrid right away rather than having to go back in my code and and get it done. To break it down further, my question is: How do I create a datagrid view automatically on a table that has been created and added to MSSQL through my c# application?


For filling it manually, firstly fill a DataTable with the query results and assign it as dataSource to the gridview

The code explains itself i hope

String xConnStr=""; //connection string goes here
SqlConnection xConn = new SqlConnection(xConnstr);
SqlCommand sqlCmd;
SqlDataReader sqlReader;
string sqlCmdString = "";
DataTable dt = new DataTable();

   sqlCmdString = "SELECT * from " + xNewTableName;
   sqlCmd = new SqlCommand(sqlCmdString, xConn);

   if (xConn.State == ConnectionState.Closed)

   sqlReader = sqlCmd.ExecuteReader();

   dataGridView1.DataSource = dt;

You might need this:

using System.Data.SqlClient;
using System.Data;