我正在尝试使用Visual Studio显示来自SQL Server的数据网格,并且在屏幕快照中显示了此错误。我在这里尝试了所有方法,但未找到任何答案,请查看该屏幕截图。谢谢
[那是有错误的照片]
答案 0 :(得分:0)
如果要开发Web应用程序,请转到下面的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 Server获取数据
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;
}
}
最后从您的主代码中调用class方法,并将其绑定到网格视图
string TSQL = "select * from TableA";
DataTable dt =ClassSQL.RunSQL_DML_FillDataGrid(TSQL);
GridView1.DataSource = dt;
GridView1.DataBind();
您还可以在其他应用程序类型(控制台,桌面,MVC)上使用此功能,也可以将其用作直接功能,只要您对一些代码进行一些调整即可。