Reputation: 35
I am trying to get a connection from my webapp to a database to get values for a dropdownlist but somehow I always get the same Error at the con.Open. Tells me networkname was not found!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT HobbyId, Hobby, IsSelected FROM Hobbies";
//string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection("server=localhost/testserver; database=MyDB.dbo; integrated security=true"))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Hobby"].ToString();
item.Value = sdr["HobbyId"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
ddlHobbies.Items.Add(item);
}
}
con.Close();
}
}
ddlHobbies.Items.Insert(0, new ListItem("--Select Hobby--", "0"));
}
}
Upvotes: 0
Views: 95
Reputation: 13063
You need to use a backward slash (\
) instead of a forward slash (/
): server=localhost/testserver
should be server=localhost\testserver
.
You can also replace localhost
with a simple dot (.
): server=.\testserver
.
Make sure that your SQL server instance is actually running. You can open SQL server configuration manager to check this.
You will also need to enable at least one network protocol for your instance (e.g. named pipes, TCP/IP or shared memory).
Upvotes: 3