The Angry Saxon
The Angry Saxon

Reputation: 792

Convert passed object into something

Basically I wanted to pass "something" to a function and then in the function find out what it was and add an item according

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var db = new Data.SQLDataContext();
        ddlSubject.DataSource = db.CONTACTSUBJECTs.Where(p => p.Live == true).OrderBy(p => p.Weight);
        ddlSubject.DataBind();

        //ddlSubject.Items.Insert(0, new ListItem("- Please select message subject -", "No subject given"));

        AddItem(ddlSubject, "- Please select message subject -", "No subject given", 0);
    }
}

protected void AddItem(object o, string t, string v, int i)
{
    var item = o.GetType().ToString();
    switch (item)
    {
        case "System.Web.UI.WebControls.DropDownList":
            (DropDownList) o.Items.Insert(i, new ListItem(t, v));
            break;
    }
}

Hopefully the code will explain better than I am. I just wondered if it were possible.

Upvotes: 1

Views: 76

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

There are many different solutions to this. Firstly, what you're doing will actually probably work but it's definitely the wrong way to go about it.

You could:

Use the is keyword:

protected void AddItem(object o, string t, string v, int i)
{
    if(o is DropDownList) {
        ((DropDownList) o).Items.Insert(i, new ListItem(t, v));
    }
}

Use overloads:

protected void AddItem(DropDownList dropDown, string t, string v, int i) {
    dropDown.Items.Insert(i, new ListItem(t, v));
}

protected void AddItem(Label l, string t, string v, int i) { 
    l.Text = t + v + i;
}

AddItem(ddlSubject, "- Please select message subject -", "No subject given", 0);
AddItem(lblSubject, "Hello", "World", 15);

Use a generic class? Can't think of an example of doing this via generics that would be any better/quicker than using overloads, but it's absolutely possible.

Upvotes: 4

Related Questions