Marci
Marci

Reputation: 319

Sort Datagridview with datasource a list

I have a Datagridview (dataGridView1) and the datasource is a list (Bets). I'd like to order it by a column value Ascending (odd1). How Could I do it?

EDIT: Maybe I should order list before fill datagridview? any suggestion?

EDIT2: I got the solution, but numbers are in a wrong progress. Check pic:

enter image description here

After 1.99 I'd like to have 2.00 instea of 10.57. How Can I do it?

EDIT3: This is a piece of my class:

public string odd1 { get { return (Odds.Count >= 3) ? Odds[0] : "error"; } set { if (Odds.Count >= 3) Odds[0] = value; } }

public string oddX
{
    get { return (Odds.Count >= 3) ? Odds[1] : "error"; }
    set { if (Odds.Count >= 3) Odds[1] = value; }
}

public string odd2
{
    get { return (Odds.Count >= 3) ? Odds[2] : "error"; }
    set { if (Odds.Count >= 3) Odds[2] = value; }
}

Upvotes: 0

Views: 877

Answers (1)

Zein Makki
Zein Makki

Reputation: 30052

You can simply use Linq before setting the gridView's datasource:

Edit: Since the type of odd1 is string, you need to convert it to a number to get the desired results. Since not all the numbers are valid, you need to do some checking in order to get the desired result.

list = list.OrderBy(x=> ConvertFromString(x.odd1)).ToList();

define a method:

private decimal ConvertFromString(string str)
{
    decimal val = decimal.MaxValue;

    if (decimal.TryParse(str, out val))
        return val;
    else
        return decimal.MaxValue;
}

Or in-place sorting without creating a new list:

list.Sort((x, y) =>  (int)(Decimal.Parse(x.odd1) -  Decimal.Parse(y.odd1)));

Upvotes: 2

Related Questions