问题描述
你好
我有一个Visual Web部件,在.ascx文件中,有下面一行用于连接到SQL数据库.
I have a Visual Web Part and in the .ascx file I have the below line which is used to connect to a SQL Database.
<!-SQL数据源->
< asp:SqlDataSource ID =" SqlDataSourceContent" runat =服务器" ConnectionString =<%$ ConnectionStrings:ContentConnectionString%>" SelectCommand ="SELECT * FROM [Content]" ProviderName ="<%$ ConnectionStrings:ContentConnectionString.ProviderName %>></asp:SqlDataSource>
<!-- SQL Data Source -->
<asp:SqlDataSource ID="SqlDataSourceContent" runat="server" ConnectionString="<%$ ConnectionStrings:ContentConnectionString %>" SelectCommand="SELECT * FROM [Content]" ProviderName="<%$ ConnectionStrings:ContentConnectionString.ProviderName %>"></asp:SqlDataSource>
虽然以上行在代码"或设计器"视图中突出显示,但是我可以在属性"窗格中看到ConnectionString字段列出了正确的信息(我删除了此信息).
While the above line is highlighted in Code or Designer view I can see in the Properties pane that the ConnectionString field has the correct information listed (I removed the info for this post).
数据源=< hosturl> ;;初始目录=<数据库名称> ;;用户ID =<用户名> ;;密码=<密码>
Data Source=<hosturl>;Initial Catalog=<databasename>;User ID=<username>;Password=<password>
在运行代码时,我收到一条错误消息,指出"ContentConnectionString不存在或为空".
Upon running the code I get a error that says "ContentConnectionString does not exist or is null".
我不确定为什么没有信息传递给应用程序.我尝试将连接信息添加到app.config中,但是不确定如何告诉SqlDataSource使用它.另外,由于这是一个新项目,因此除了ascx.cs中的默认代码外,没有其他代码 文件.我认为运行可视化Web部件并初始化sql连接不需要任何代码,尤其是因为我仅使用设计器添加了一些文本元素和Formview,但我可能是错的.
I am unsure why no information is passed to the application. I made a attempt to add connection info to app.config but I am unsure how to tell the SqlDataSource to use that. Also since this is a new project there is no code besides the default code in ascx.cs file. I don't believe that any code is needed to run the visual web part and initialize the sql connection especially since I only added a few text elements and a formview using the designer but I could be wrong.
推荐答案
首先,将连接字符串存储到App.config中,如下所示:
Firstly, store the connection string into App.config like below:
<appSettings>
<add key="ConnStr" value="Server=yourservername;Database=yourdatabasename;UID=yourusername;Password=youruserpassword"/>
</appSettings>
然后在SqlDataSource中引用连接字符串:
Then reference the connection string in SqlDataSource:
<asp:GridView ID="grd" runat="server" DataSourceID="SqlDataSource2">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%
这里有一个类似的线程供您参考:
Here is a similiar thread for your reference:
https://stackoverflow.com/questions/16187407/defining- connectionstring-in-asp-sqldatasource
更多信息:
如何:使用SqlDataSource控件连接到SQL Server数据库
谢谢
这篇关于使用设计器设置时,Visual Web部件SqlDataSource ConnectionString显示为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!