No value set for one or more required options when changing DropDownlist

Just two descents

Retrieving values ​​from a database, for example:

Drop DOWN 1 (Products)

  • Ice cream
  • Chocolate
  • Cold drinks

if from the first dropdown list 1 of the selected ice cream will be displayed

Drop Down 2 (varieties)

  • Vanilla
  • Strawberry
  • Mango

if Candy is selected from the first dropdown list 1, it will display

Drop Down 2 (varieties)

  • Dark chocolate
  • Milk chocolate
  • Caramel chocolate

Other items should be cleared and only displayed above.


Code used

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string txtval = DropDownList1.SelectedValue;
    string txtval1 = DropDownList1.SelectedItem.Text;

    string str = "Provider=Microsoft.ACE.OleDB.12.0; Data Source=C:\\Users\\user\\Desktop\123\\WebSite1\\Checking_Db.mdb";
    OleDbConnection db = new OleDbConnection(str);
    db.Open();                                    
    //  string st = "select Emp_Ph_No from emp where Emp_Name =  DropDownList1.SelectedValue ;";

    string st = "select Emp_Ph_No from emp where Emp_Name = txtval1;";

    OleDbCommand dbc = new OleDbCommand(st, db);
    OleDbDataReader read = dbc.ExecuteReader();

    DropDownList2.DataSource = read;
    DropDownList2.DataTextField = "variety";       
    DropDownList2.DataValueField = ""variety";       
    DropDownList2.DataBind();
    read.Close();
    db.Close();
}

      

+3


source to share


1 answer


The problem is in this line;

...where Emp_Name = txtval1;

      

If txtval1

is string

, you have to use it as Emp_Name = 'txtval1'

. This is invalid syntax. In this case, the OLEDB provider thinks this txtval1

is a parameter and you haven't entered any value for that.

You can set this value as a parameter and add to your command:



string st = "select Emp_Ph_No from emp where Emp_Name = ?";
OleDbCommand dbc = new OleDbCommand(st, db);
dbc.Parameters.AddWithValue("?", txtval1);

      

I used AddWithValue

in my example, but you don't . This method can sometimes generate unexpected results . Use overloads .Add()

to specify your parameter OleDbType

and size.

Also use using

statement
to manually delete your connection, command and reader instead of callind .Close

or .Dispose

.

using(var db = new OleDbConnection(str))
using(var dbc = db.CreateCommand)
{
    // Set your CommandText.
    // Add your parameter value.

    using(var read = dbc.ExecuteReader())
    {
       //
    }
}

      

+3


source







All Articles