Sepehr Kazemi Sepehr Kazemi - 11 months ago 78
ASP.NET (C#) Question

Getting asp:SqlDataSource Connection String dynamically from a method (Without Webconfig)

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?

Answer Source

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


public static SqlConnection getConnection()
    SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=yourDB;User ID=yourUser;Password=pa$$w0rd");
    return conn;


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;