0

I have multiple dynamically generated dropdownlists bound with database. I want the shortest string value to be shown at index 0 in each dropdown.

The sample code is:

DropDownList ddlTemplate = new DropDownList();
ddlTemplate.ID = "ddlTemplate|" + j.ToString();
ddlTemplate.AppendDataBoundItems = true;
ddlTemplate.DataTextField = "TemplateName";
ddlTemplate.DataValueField = "TemplateName";
ddlTemplate.Width = Unit.Pixel(200);
ddlTemplate.AutoPostBack = true;
ddlTemplate.DataSource = null;
ddlTemplate.DataSource = dsMultipleTemplate.Tables[j].DefaultView;
ddlTemplate.DataBind();

If it can be achieved through database query please guide me.

Thanks

naeemmalik
  • 67
  • 2
  • 11
  • 1
    What did you try so far? First approach that comes to my mind is looping the elements, get each elements length and return this element with shortest. Ofc. this can also be done with LINQ. Where is the problem? – MakePeaceGreatAgain Jun 25 '15 at 10:51

1 Answers1

0

As you arnt answering to the comment, maybe you are looking for something like that:

    List<int> stringLength = new List<int> { }; // storing every length

    foreach (string entry in ddlTemplate.Items)
    {
        stringLength.Add(entry.Length); // saving each string-length
    }

    int index = stringLength.FindIndex(a => a == stringLength.Min()); // get index of lowst length
    ddlTemplate.SelectedIndex = index; // set selected value to index from above

This way, your item wouldnt be at index 0, but it would be selected. Placing it to index 0 is very basic. I guess you can do this on your own.

C4d
  • 3,183
  • 4
  • 29
  • 50
  • 1
    Thanks for your help, this is the best ans i got so far. @HimBomBeere also answered well but didn't know how to implement it. I got error at cast from list item to string but manage to solve it :) – naeemmalik Jun 25 '15 at 18:05
  • Yeah Im not that experienced with asp.net. Therefore I havnt dealed with the DropDownList before. I could just imagine it could be handled like a comboBox-control. Was written from mind. Glad I could help. – C4d Jun 26 '15 at 08:50