Monday, March 26, 2012

Pass value to second DropDownList from the first one

I want pass value to 2nd DropDownList from 1st one. I use "DropDownList1.SelectedValue", but got error message." can't transfer data type from varchar,..." Yes, in Database, it is varchar type.

Here is a source code:

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string sql = "select Address from myTable where Name=" + DropDownList1.SelectedValue ;
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds, "myTable");
DataView dv=ds.Tables [0].DefaultView ;

DropDownList2.DataTextField="Address";
DropDownList2.DataValueField ="Address";
//DropDownList2.DataSource =ds.Tables[0].DefaultView;
DropDownList2.DataSource=dv;
DropDownList2.DataBind ();

con.Close();
}

Two things.

1) I would use a SqlDataReader to populate the DropDownList. It is 100x faster than a DataSet.

2) Try DropDownList1.SelectedItem.Value to get the value of the DropDownList


move your datasource code line above both your datatextfield and datavaluefield

[edit]

He is right about the speed--much faster.


I did try: DropDownList1.SelectedItem.Value, but got same error msg.

You are missing the single quotes around the parameter, try:

string sql = "select Address from myTable where Name='" + DropDownList1.SelectedValue + "'" ;


Better NOW.

0 comments:

Post a Comment