ZedBee
ZedBee

Reputation: 2378

Concatenating with DropDownList items ASP.Net

I have a databound dropdownlist on my asp.net page.

<asp:DropDownList ID="ddlCases" runat="server"></asp:DropDownList>

I am populating ddlCases as

ddlCases.DataSourse = SelectItems();
ddlCases.DataValueField = "itemid";
ddlCases.DataTextField = "itemname";
ddlCases.SelectedIndex = 0;
ddlCases.DataBind();

SelectItems() return a datatable. What I want to do is to concatenate each item with a sequence number(1,2,3..) in which sequence they appear in the dropdownlist something like 1. itemname1 2. itemname2 3. itemname3

What are my options for achieving this?? Regards, ZB

Upvotes: 1

Views: 276

Answers (2)

Mahmoud Farahat
Mahmoud Farahat

Reputation: 5475

you can handle the databound event and edit items in the list , try this code :

   protected void ddlCases_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ddlCases.Items.Count; i++)
        {
            ddlCases.Items[i].Text = i + 1 + ". " + ddlCases.Items[i].Text;
        }
    }

Upvotes: 1

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

You can do it with linq, something like this should work

ddlCases.DataSourse = SelectItems().Select((item, index) 
                                             => new{
                                                     index = index, 
                                                     itemid = item.itemid, 
                                                     itemname = index.ToString() + "." + item.itemname
                                                    });
ddlCases.DataValueField = "itemid";
ddlCases.DataTextField = "itemname";
ddlCases.SelectedIndex = 0;
ddlCases.DataBind();

EDIT

Select method creates another IEnumerable(collection) that contains new anonymous type,where index property is index in the first array, itemid is itemid and itemname index + itenmane

So shortly with LINQ statments we create another temporary class, that contains properties we want

Hope this make sense

EDIT

If SelectItems method returns untyped data table, as @VinayC suggested in the comment you should write

ddlCases.DataSourse = SelectItems()
.AsEnumerable().Select((r, i) => new { itemid = r["itemid"], itemname = i.ToString() + r["itemname"] })

Upvotes: 0

Related Questions