1

I have a DropDownList which is filled up from database. When I select a record on index 1, it comes up with right results but when I select second index, it comes up with same index. it looks like DropDownList shows First Index as by default. How can I select change index in DropDownList? So if would select index 3 the result must be from index 3. I have tried DropDownList.SelectedItem,DropDownList.SelectedValue,DropDownList.SelectedIndex,DropDownList.Text but No effect seems to be there.

DropDownList Loading on Page_Load

 public void load_Individual()
    {
        if (IsPostBack == false)
        {
            SqlDataAdapter sdaIndividual = new SqlDataAdapter("select * from tbl_trip", _connectionString);
            DataTable dtIndividual = new DataTable();
            sdaIndividual.Fill(dtIndividual);
            if (dtIndividual.Rows.Count > 0)
            {
                ddl_Individual.DataTextField = "TruckNo";
                ddl_Individual.DataValueField = "TruckNo";
                ddl_Individual.DataSource = dtIndividual;
                ddl_Individual.DataBind();
            } 
        }
    }

DropDownList For Selecting Values

if (ddl_Individual.Text != string.Empty)
        {
            ddl_Individual.ClearSelection();
            adp = new SqlDataAdapter(@"Select * , '' as c1, '' as c2, 0 as c3 , 0 as c4 , 0 as c5 , 0 as c6, 0 as c7 , 0 as c8 from tbl_Trip 
            where TruckNo='" + ddl_Individual.SelectedValue + "'", _connectionString);
            adp.Fill(Dt);
            Session["mydata"] = Dt;
            Response.Redirect("LoadReport.aspx");
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(),"alertMessage","aler('select valid value')", true);
        }

1 Answer 1

1
ddl_Individual.ClearSelection();

This line is clearing the selection in the dropdown before you have a chance to read what value the user has selected. Remove it as I see no need for it.

Make sure to set the items in the page load by checking for a postback:

if(!IsPostBack)   
{
    // Perform binding
} 

If the dropdown should trigger the postback then be sure to set the AutoPostBack = true;

Also, look into using parameterized queries to help prevent SQL injection attacks. This is a good habit to develop regardless of the size of the application.

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried this, but there is no effect. kindly share an alternate solution please
Actually my application is a small application and there is no need to use Sql Injection. So would you like to share an other alternate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.