我在DataGrid中有一个Amounts
列,我需要在TextBox中求和并显示。我已尝试循环遍历DataGrid行,但无法找到正确的语法。 DataGrid绑定到基于IEnumerable
的{{1}}。这是代码;
TransactionModel
TransactionModel
XAML绑定到DataGrid
public class TransactionModel
{
public int TransactionID { get; set; }
public string TransactionText { get; set; }
public int TransactionAmount { get; set; }
public DateTime TransactionDate { get; set; }
public string TransactionMonth { get; set; }
}
填充TransactionModel
<DataGrid x:Name="dataGrid" Margin="5" AutoGenerateColumns="False" HeadersVisibility="Column" SelectionMode="Single" CanUserAddRows="False" CanUserDeleteRows="False" FontSize="20">
<DataGrid.Columns>
<DataGridTextColumn Header="Transaction" Width="*" Binding="{Binding TransactionText}"/>
<DataGridTextColumn Header="Transaction Amount" Width="*" Binding="{Binding TransactionAmount}"/>
<DataGridTextColumn Header="Transaction Date" Width="*" Binding="{Binding TransactionDate}"/>
<DataGridTextColumn Header="Transaction Month" Width="*" Binding="{Binding TransactionMonth}"/>
</DataGrid.Columns>
</DataGrid>
如何循环显示public IEnumerable<TransactionModel> GetTransactionList()
{
string constr = ConfigurationManager.ConnectionStrings["sqlString"].ConnectionString;
using (var sqlCon = new MySqlConnection(constr))
{
sqlCon.Open();
using (var myQuery = sqlCon.CreateCommand())
{
myQuery.CommandText = "SELECT id, text, amount, date, month FROM financesystem.transactions ORDER BY id";
using (var myReader = myQuery.ExecuteReader())
{
var transactionList = new List<TransactionModel>();
while (myReader.Read())
{
var details = new TransactionModel
{
TransactionID = Convert.ToInt32(myReader[0]),
TransactionText = myReader[1].ToString(),
TransactionAmount = Convert.ToInt32(myReader[2]),
TransactionDate = Convert.ToDateTime(myReader[3], System.Globalization.CultureInfo.CurrentCulture),
TransactionMonth = myReader[4].ToString(),
};
transactionList.Add(details);
}
return transactionList;
}
}
}
}
中显示的值并将它们相加以显示在DataGrid
?
答案 0 :(得分:1)
你可以使用IEnumerable的回报来计算总和吗?如果是这样,LINQ很容易:
int amountSum = GetTransactionList().Sum(model => model.TransactionAmount)