Question

I've got the code below and am getting the error

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
    SqlConnection vid = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\\Users\\jlm\\Desktop\\Wk5ex01vbMills\\AdventureWorksDW_Data.mdf;Integrated Security=True;Connect Timeout=30");

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

       try 
          {         

           string str = TextBox1.Text;
           SqlCommand xp = new SqlCommand(str, vid);

           vid.Open();
           xp.ExecuteNonQuery();

           SqlDataAdapter da = new SqlDataAdapter();
           da.SelectCommand = xp;
           DataSet ds = new DataSet();
           da.Fill(ds);
           GridView1.DataSource = ds;
           GridView1.DataBind();
           vid.Close();
          }

       catch (Exception c)
          {
                Label1.Text = (c.Message);
          }
    }
  }
}
Was it helpful?

Solution

You need to escape \ in your connection string in a part (LocalDB)\v11.0. Should be localdb)\\v11.0.

That said - it's really risky to allow entering raw SQL to be executed against your DB. Even if you take all precautions not to allow dangerous commands - there's always a chance that something can slip thru.

enter image description here

OTHER TIPS

public partial class _Default : Page
{
    SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\rinka.sai\\Desktop\\WebApplication1\\App_Data\\Database1.mdf;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {


    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(TextBox1.Text,conn);
        SqlDataReader sdr = cmd.ExecuteReader() ;
        GridView1.DataSource = sdr;
        GridView1.DataBind();
        sdr.Close();
        conn.Close();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top