开发者

Need help in c# code

开发者 https://www.devze.com 2023-01-02 03:49 出处:网络
I have a function protected void bindCurrencies(DropDownList drp) { drp.DataSource = dtCurrencies; drp.DataTextField = \"CurrencyName\";

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 bi开发者_JS百科nd 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消