【问题标题】:I am trying to display data grid from Visual Studio with SQL Server我正在尝试使用 SQL Server 从 Visual Studio 显示数据网格
【发布时间】:2019-05-09 20:27:23
【问题描述】:

我正在尝试使用 Visual Studio 从 SQL Server 显示数据网格,并且屏幕截图中显示了此错误。我在这里尝试了所有方法,但没有找到任何答案,请查看该屏幕截图。谢谢

[那是有错误的照片]

【问题讨论】:

  • 我看不到照片,粘贴一些代码也会有所帮助。
  • 您好,感谢您告知我们。我会尝试重新上传或将代码粘贴到此处。

标签: c# frameworks entity


【解决方案1】:

如果您正在开发网络应用程序,请转到 web.config 文件添加下面,根据您的 SQL 环境设置更改参数。

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

然后构建一个类文件,假设我们将其命名为“ClassSQL”,然后构建一个能够使用 TSQL 从 SQL 服务器获取数据的子方法

 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;
        }
    }

最后从你的主代码中调用类方法并将其绑定到网格视图

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

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

您也可以在其他应用程序类型(控制台、桌面、MVC)上使用它,或者将其用作直接函数,只要您稍微调整一下代码即可。

【讨论】:

  • 如果有帮助请标记为答案(点击▲),谢谢:)
猜你喜欢
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多