Reputation:
Trying to set sql server from a class in asp:sqldatasource tag:
Public static SqlConnection getConnection()
{
SqlConnection conn = new SqlConnection();
//rest of the code that 100% works
return conn;
}
This function is tested in C# code and it works 100%. Now I'm trying to use it in an asp:SqlDataSource:
<asp:SqlDataSource runat="server" ID="sqlDBConnection"
ConnectionString="<%# inProcessInventory.DataTools.getConnection().ConnectionString %>"
I receive:
The ConnectionString property has not been initialized
Any suggestion?
Upvotes: 3
Views: 2036
Reputation: 640
We often use SqlConnection and set Connectionstring directly or Call from configurationManager(in Asp.net). Do you know about SqlConnectionStringBuilder Class. It is under namespace System.Data.SqlClient .
You can use this class to set Connectionstring values in SqlConnection Class. Here is the code:
SqlConnection myConnection = new SqlConnection();
SqlConnectionStringBuilder myBuilder = new SqlConnectionStringBuilder();
myBuilder.UserID = "sa";
myBuilder.Password = "sa123";
myBuilder.InitialCatalog = "DbName";
myBuilder.DataSource = "ServerName";
myBuilder.ConnectTimeout = 30;
myConnection.ConnectionString = myBuilder.ConnectionString;
Upvotes: 0
Reputation:
Credit: https://forums.asp.net/t/1072016.aspx?Dynamic+connection+strings
If your connection string is created dynamically at run time. We cannot set the connection string at design time.
Binding to the property might not work since this depends on when you call DataBind on your controls.
In this case, it's better to set this in code behind event handler for Page_Load like
Me.dsTest.ConnectionString = objClientConnection.ConnectionString
Then you can call DataBind() manually.
Upvotes: 1
Reputation: 35514
A ConnectionString is, as the name implies, a string. You are returning a SqlConnection
where a string is expected.
public static string getConnection()
{
return "Data Source=localhost;Initial Catalog=yourDB;User ID=yourUser;Password=pa$$w0rd";
}
Or
public static SqlConnection getConnection()
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=yourDB;User ID=yourUser;Password=pa$$w0rd");
return conn;
}
UPDATE
It does work correctly if you set the connection string in code behind:
protected void Page_Load(object sender, EventArgs e)
{
sqlDBConnection.ConnectionString = inProcessInventory.DataTools.getConnection().ConnectionString;
}
Upvotes: 2