How to get the selected value from a selectbox in LinqPad?

Viewed 61

This example is from the linqpad help file.

var yourChoice = new DumpContainer();
string[] colors = { "Red", "Green", "Violet", "Blue", "Orange", "Yellow" };

// Dropdown-style select box:
var selectBox = new SelectBox (colors, 0,
    sb => yourChoice.Content = sb.SelectedOption
).Dump ("Choose a color");
yourChoice.Dump ("Your choice(s)");

Question1: I can get the selected value using yourChoice.Dump(), but how can I get the selected value as a string? in the real case scenario the dropdown is a list of customers, after selecting the customer I need to pass the customer name to other methods.

Question2: is there anyway I can set both a submit value and text in the SelectBox, so that the submitted value is different than the displayed value

2 Answers

If you wanted to use the SelectBox in a procedural way, you could use a TaskCompletionSource:

var colors = new Dictionary<string, string>
{
    { "Red", "RedValue"},
    { "Violet", "VioletValue"},
    {"Blue", "BlueValue" }
};

var tcs = new TaskCompletionSource<string>();
var selectBox = new SelectBox(colors.Keys.ToArray(), 0, sb =>
{
    tcs.SetResult(colors[sb.SelectedOption.ToString()]);
    sb.Enabled = false;
}).Dump("Choose a color");

var result = await tcs.Task;

result.Dump("Your choice");

You could obviously do the same with a TaskCompletionSource<Customer> if you override ToString as in @sgmoore's answer.

Here are a few examples using an array of customers.

You can pass the names to the control and return the name and/or the index of the selected item to your method.

If you can override ToString() on your class, then you can just pass your array of customers and pass the selected customer to your method.

Customer[] customers ;
void Main()
{
    customers = new Customer[] {
        new Customer{ ID = 1, Name = "Joe Bloggs"},
        new Customer{ ID = 2, Name = "Mary Bloggs"},
        new Customer{ ID = 3, Name = "John Brown"}
    } ;

    var names = customers.Select(a => a.Name).ToArray();
    new LINQPad.Controls.SelectBox(names, 0, sb => SelectionChanged(sb.SelectedOption, sb.SelectedIndex)).Dump("Choose a customer");


    new LINQPad.Controls.SelectBox(customers, 0, sb =>   Selection2Changed(sb.SelectedOption)  ).Dump("Choose a customer");
             
}

void SelectionChanged(object selectedOption, int index)
{
    var selectedName = selectedOption as string;

    Console.WriteLine($"You selected {selectedName}");
    
    customers[index].Dump();
}

void Selection2Changed(object selectedOption)
{
    var selectedCustomer = selectedOption as Customer;


    selectedCustomer.Dump();
}

public class Customer
{
    public int ID;
    public string Name;
    
    public override string ToString()
    {
        return Name; 
    }
}
Related