I want to pass only e.Trip
of my string.Format
to the method referenced in tripChoose
. As of now, it tried to pass a string not formatted for the method. If I could just pass the Trip part of the string, it would work. Any suggestions?
private void LoadExpenseListSums()
{
expenseTotalSelect.Items.Clear();
var sortedList=
from e in roster
group e by e.Trip into expenseCollect
select new { Trip = expenseCollect.Key, SumAmount = expenseCollect.Sum(e => e.Amount) };
foreach (var e in sortedList)
tripChoose.Items.Add(string.Format("{0} | ${1}", e.Trip, e.SumAmount));
}
It looks like your expenseTotalSelect is an ASP.NET Select control and what you're doing ends up adding an element in the result HTML identified only by text such as:
<select id='expenseTotalSelect'>
<option>Hawaii | $5000</option>
<option>London | $4000</option>
...
</select>
In your expenseTotalSelect.Items.Add call you would probably be better off doing the following:
expenseTotalSelect.Items.Add(
new ListItem(string.Format("{0} | ${1}", e.Trip, e.SumAmount),e.Trip));
Now you'll get the following when you render to HTML:
<select id='expenseTotalSelect'>
<option value='Hawaii'>Hawaii | $5000</option>
<option value='London'>London | $4000</option>
...
</select>
And it will be easier to just reference tripChoose.SelectedItem.Value
which will only contain the e.Trip value (Hawaii or London) for this example
Right, now we actually know what we're dealing with, I suspect you want something like this:
private void LoadExpenseListSums()
{
expenseTotalSelect.Items.Clear();
var dateSorted =
from e in roster
group e by e.Trip into tripGroup
select new { Trip = tripGroup.Key,
Text = string.Format("{0} | ${1}",
tripGroup.Key,
tripGroup.Sum(e => e.Amount) };
tripChoose.DataSource = dateSorted;
tripChoose.DisplayMember = "Text";
tripChoose.ValueMember = "Trip";
}
This makes a few assumptions: ase, - roster
is an in-memory collection: if it's not, you'll probably need an AsEnumerable
call before the formatting, to make that happen locally - Anonymous types work with data binding; I'm not sure whether that's the case, but I'd hope it is
You then use the SelectedValue
member later on to find the trip ID.
认为您应该使用注释中建议的对象,但假设expenseTotalSelect
是List<string>
并且tripChoose
绑定到它,您可以这样做:
(string)tripChoose.SelectedItem.Split('|')[0].Replace(" ", string.Empty)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.