I am trying to display data grid from Visual Studio with SQL Server

可紊 提交于 2021-01-29 12:12:12

问题


I am trying to display data grid from SQL Server with Visual Studio and I have this error shown in the screenshot. I have tried everything here and did not find any answers please see that screenshot. Thank you

[that is the photo with the error]


回答1:


If you are developing web apps , go to web.config file add below , change parameter according your SQL environment setup.

<configuration>
    <connectionStrings>  
            <add name="PSDatabaseConnectionString" connectionString="Data Source=YourSQLserverName\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient"/>
    </connectionStrings>
....

then built a class file , let say we name it as "ClassSQL" and then built a sub method that able get data from SQL server using TSQL

 public static DataTable RunSQL_DML_FillDataGrid(string TSQL)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["PSDatabaseConnectionString"].ConnectionString;

        SqlDataAdapter dataAdapter;
        SqlConnection conn = new SqlConnection(connectionString);


        try
        {
            // Run TSQL on SQL server
            dataAdapter = new SqlDataAdapter(TSQL, connectionString);

            // MS Term ' Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.

            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and return the table.
            // MS Term ' Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            return table;
        }
        catch
        {
            return null;
        }
    }

Finally call the class method from your main code and bind it to grid view

string TSQL = "select * from TableA";
DataTable dt =ClassSQL.RunSQL_DML_FillDataGrid(TSQL);

GridView1.DataSource = dt;
GridView1.DataBind();

You can use this on other application type ( console , desktop , MVC) as well , or as a direct function , as long as you tweak a bit some of the code.



来源:https://stackoverflow.com/questions/56067070/i-am-trying-to-display-data-grid-from-visual-studio-with-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!