简体   繁体   中英

Need help in c# code

I have a function

protected void bindCurrencies(DropDownList drp)
    {
        drp.DataSource = dtCurrencies;
        drp.DataTextField = "CurrencyName";
        drp.DataValueField = "CurrencyID";
        drp.DataBind();
        drp.Items.Insert(0, new ListItem("Please Select"));
    }

I am binding a dropdown list using this. But sometimes I need to bind a ListBox also. I dont want to write a different function for listbox. How should I do this. I think Generics method is to be used here. But I dont have any idea about generics.

Both DropDownList and ListBox inherit from ListControl , so if you change your function to take a ListControl as parameter, it should work well with both types:

protected void bindCurrencies(ListControl drp)
{
    drp.DataSource = dtCurrencies;
    // and so on...

Ask for a ListControl instead. Both ListBox and DropDownList inherit it, so you can use it to contain both.

Generics is (in most cases) used if you need a class of something . For example, a list of strings would be a List in generics.

Pass the parameter as an Object, then simply use the object's:

.Getype()

around a select statement and cast it to that type.

Unlike the other solutions of Passing a ListControl, this will allow you to pass other controls types (and expand the logic as required).

EDIT 1 (in response to Sebastian):

 private void bindCurrencies(object PControl)
 {
    switch (PControl.GetType.ToString) {
        case "Windows.Forms.ListBox":
            Windows.Forms.ListBox ctrl = (Windows.Forms.ListBox)PControl;
            break;
        //Do Logic'
        case "Windows.Forms.DropDownList":
            break;
            //etc 
            //etc
    }
  }

always remember: KISS (Keep It Simple Stupid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM