0

I am trying to create a web application that will use a DropDownList to have a user choose a certain value and a DataList to show certain data. For instance, if the user selects a value from the DropDownList, only data related to the user selected value should be shown in the DataList. I am very new to ASP.NET and to C#.

The code below is what I have implemented in my code behind file. Currently I am getting an ArgumentException error I am not sure how to resolve this issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Products : System.Web.UI.Page
{
    SqlDataAdapter adapter;
    DataSet dset;
    string connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|@Registration.mdf;Integrated Security=True";
    string sql = "select * from Products";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            adapter = new SqlDataAdapter(sql, connstring); //<--ArgumentException error occurs here
            dset = new DataSet();
            adapter.Fill(dset);
            DropDownList1.DataSource = dset.Tables[0];
            DropDownList1.DataTextField = "CategoryName";
            DropDownList1.DataValueField = "ProductID";
            DropDownList1.DataBind();
            DataListBind();
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataListBind();
    }
    public void DataListBind()
    {
        adapter = new SqlDataAdapter("select * from Products where ProductID=" + DropDownList1.SelectedValue + "", connstring);
        dset = new DataSet();
        adapter.Fill(dset);
        dlProducts.DataSource = dset.Tables[0];
        dlProducts.DataBind();
    }
}
Keith Code
  • 57
  • 8
  • Check your connection string, if it is correct one. – mybirthname Dec 08 '16 at 07:31
  • @mybirthname I copied and pasted the connection string from the `Web.config` file. My connection string has a name and I tried that, and still get the same error. So instead I thought it would fix the issue by directly copying and pasting the connection string itself. – Keith Code Dec 08 '16 at 07:38

2 Answers2

0

The problem is you connection string. If you look at the inner exception that you get it says:

Invalid value for key 'attachdbfilename'

This post is further help on this matter.

To get rid of the exception just add a @ in front of the string:

string connstring = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|@Registration.mdf;Integrated Security=True";
Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
0

You have'nt created a connection object. I think you need to create and open the connection first.

Nikunj Kakadiya
  • 2,689
  • 2
  • 20
  • 35