locked
ListControl doesn't accept ListBoxes in C# RRS feed

  • Question

  • User755602676 posted

    I'm converting a project from VS 2003 to VS 2005. Furthermore, I'm translating from VB.Net to C#. In my VB.Net code, I have a method in a class that requires a ListControl parameter. When I call this method, I sometimes pass a ListBox and sometimes a DropDownList. This works fine in VB.Net, but C# doesn't like it ("cannot convert from 'ref System.Web.UI.WebControls.ListBox' to 'ref System.Web.UI.WebControls.ListControl'). Is there a type I can use for the method's parameter that will accept both ListBox and DropDownList types?

    Thank you.

    Thursday, February 28, 2008 12:08 PM

Answers

  • User-833064204 posted

    Try removing the "ref" in your parameter declaration. In C#, objects are, by default, passed in as reference parameters (instead of value parameters). So if you remove the "ref", you'll still pass the control in by reference, and the type conversion should take place.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 28, 2008 1:13 PM

All replies

  • User-833064204 posted

    Try removing the "ref" in your parameter declaration. In C#, objects are, by default, passed in as reference parameters (instead of value parameters). So if you remove the "ref", you'll still pass the control in by reference, and the type conversion should take place.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 28, 2008 1:13 PM
  • User1470508873 posted

    The simples thing to do is the copy and paste the same method, and change the paramater type.  This way both methods will work, based on what is passed int.  So if you have

    void DoSomethiig( System.Web.UI.WebControls.ListBox)

    {

          //Blah Blah

    }

    void DoSomethiig( System.Web.UI.WebControls.DropDownList)

    {

          // Same Blah Blah

    }

     when calling the methods, it will know which one to go to...

    Thursday, February 28, 2008 1:21 PM
  • User755602676 posted

    This did it. Thanks! But how strange...

    Thursday, February 28, 2008 1:23 PM
  • User1470508873 posted

    Another approach is change the paramater to a Control, and in the method check the control type... So if you have your method as :

     

    private void MyMethod(System.Web.UI.WebControls.DropDownList)
    {
        //your code
    }
    
    //Make It Into
    private void MyMethod(System.Web.UI.Control ct)
    {
        if ( ct is DropDownList)
        {
                 //your code with DropDown
        }
        else if ( ct is ListBox)
        {
                //your code with ListBox
        }
    }
    
    
     
    Thursday, February 28, 2008 1:26 PM