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();
}
}