Selecting the shortest item string from dropdownlist in C# Asp.net

66 views Asked by At

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

1

There are 1 answers

2
C4d On BEST ANSWER

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.