Reputation: 49
I made a database using the sql server db feature in VS-2015 and am trying to nest 2 grid views. I have everything set up as wished until I get to the connection string part. I have to place the connection string in my aspx page and in my aspx.cs page. I just don't know where to find the connection string of my db located in server explorer or if there is a different way to do it because it is already in the project file
PROPER CONNECTION STRING IN PLACE ERROR
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl("GridView2");
SqlDataSource dbSrc = new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HUTDMS.mdf;Integrated Security=True"].ConnectionString;
dbSrc.SelectCommand = "SELECT * FROM textBooks WHERE thirteenISBN = '" + GridView1.DataKeys[e.Row.RowIndex].Value + "' ORDER BY BookTitle";
gv.DataSource = dbSrc;
gv.DataBind();
}
}
In my connection string I'm receiving an underline in every '\' in my connection string saying "unrecognized escape sequence" how do I negate this and use my connection string?
Upvotes: 1
Views: 408
Reputation: 17019
You're not using ConfigurationManager.ConnectionStrings
correctly.Your connection string should be stored in the web.config file under the <connectionStrings>
element:
<add name="ConnectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=HUTDMS;Data Source=(LocalDb)\v11.0;"/>
And the name
property that you specified in the web.config
file should be used as the key when using ConfigurationManager.ConnectionStrings
:
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
So the complete logic to bind the books data to the GridView could potentially look something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var ds = new SqlDataSource();
ds.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
ds.SelectCommand = "SELECT * FROM textBooks ORDER BY BookTitle";
gv.DataSource = ds;
gv.DataBind();
}
}
Output in the browser:
Upvotes: 1
Reputation: 62
You need replace |DataDirectory| to your Physical folder path like 'C:\app\myDb.mdf'
Upvotes: 0