0

I am trying to code a DropDownList that will have an OnSelectedIndexChanged event but I can't make it work.

So here's the code on my .aspx:

<asp:DropDownList ID="DDLSample" OnSelectedIndexChanged="DDLSample_SelectedIndexChanged" runat="server">
    <asp:ListItem Text="Sample1" Value="0"></asp:ListItem>
    <asp:ListItem Text="Sample2" Value="1"></asp:ListItem>
    <asp:ListItem Text="Others..." Value="2"></asp:ListItem>
</asp:DropDownList> 

And a TextBox:

<asp:TextBox  ID="txtOthers" runat="server" Visible ="false" CssClass="form-control" ></asp:TextBox>

What I plan to do is that when Others... is selected from the DropDownList, it will show the Others field.

on my aspx.cs, I have this code

protected void Page_Load(object sender, EventArgs e)
{
     DDLSample.SelectedIndexChanged += new EventHandler(DDLSample_SelectedIndexChanged);
     DDLSample.AutoPostBack = true;
}

void DDLSample_SelectedIndexChanged(object sender, EventArgs e)
{
     if (DDLFindings.SelectedValue.ToString() == "2")
         txtOthers.Visible = true;
     else
         txtOthers.Visible = false;
}

But still, I keep getting this error:

CS1061: 'sample_aspx' does not contain a definition for 'DDLSample_SelectedIndexChanged' and no extension method 'DDLSample_SelectedIndexChanged' accepting a first argument of type 'sample_aspx' could be found (are you missing a using directive or an assembly reference?)

1 Answer 1

1

The DDLSample_SelectedIndexChanged is private and your aspx cannot access the private methods. You can either remove OnSelectedIndexChanged="DDLSample_SelectedIndexChanged" from your DropDownList because you already have:

DDLSample.SelectedIndexChanged += new EventHandler(DDLSample_SelectedIndexChanged);

Or make DDLSample_SelectedIndexChanged protected:

protected void DDLSample_SelectedIndexChanged(object sender, EventArgs e)
{
    //Your code
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! protected works! can you explain why? I'm kinda new to this and I really don't know the reasons behind these codes. Thank you!
@Katherine...Because without define protected your DDLSample_SelectedIndexChanged method is private and your aspx cannot access the private method.

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.