我使用這段代碼來cast我的DataGridView,然后在另一個DataGridView顯示結果。
基本上,我正在獲取一些int值并計算它們的總和,同時還用GroupBy將這些值分組。
我在另一個DataGridView中像這樣顯示結果:
datagridview2.DataSource= Su.ToList();
我的問題是,如果單元格有一個字串值,查詢似乎就會停止。
我試著添加一個'where not'條件來排除包含字串值的行,有幾種不同的方式,但都沒有成功。
下面是我所嘗試的條件的一個例子:
.Where(row => !row.Cells[2].Value.ToString().Equals("example")
這段代碼是在datagridview_cellvaluechanged方法中:
try
{
var Su = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells[8].Value != null)
.Where(row => row.Cells[2].Value != null)
.GroupBy(row => row.Cells[8] .Value.ToString()
.Select(g => new new)
{
Gruppo = g.Key,
Serie = g.Sum(row => Convert.ToInt32(row.Cells[2].Value))。
Reps = g.Sum(row => Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[2].Value)。
百分比 = (g.Sum(row => Convert.ToDecimal(row.Cells[2] .Value)) / Convert.ToDecimal(label15.Text)) * 100 //MessageBox.Show("Formato non corretto");
}
如果成功的話,這就是DataGridView的樣子;dgv1:
column 1 | column 2 |column 3
2 3 group1
3 5 group1
4 6 group2
3 4 group3
而我在dgv2的結果中看到了這個:
column 1 | column 2 |column 3
5 8 group1
4 6 group2
3 4 group3
但是如果我在第2列中添加一個字串值,像這樣:
column 1| column 2|column 3
2 3 group1
3 5 group1
4 string group2
3 4 group3
然后我在dgv2的結果中看到這個:
column 1| column 2|column 3
5 8 group1
uj5u.com熱心網友回復:
盡管我仍然不完全確定問題是什么,我將嘗試回答你的問題。
首先,如果你不能 100% 確定某個特定單元格包含一個 Int 值,你就不應該盲目地轉換它。
有一些方法可以在轉換之前檢查它是否是一個 Int 值。一種方法是這樣的:
try
{
var Su = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells[8].Value != null)
.Where(row => row.Cells[2].Value != null)
.GroupBy(row => row.Cells[8] .Value.ToString()
.Select(g => new new)
{
Gruppo = g.Key,
Serie = g.Sum(row => {
if(row.Cells[2].Value is int rowInteger)
return rowInteger;
//如果它不是一個整數,則嘗試轉換。
//如果它不能被轉換,則回傳一個默認值(在這里是-1)。
else
{
try {
{
return Convert.ToInt32(row)
}
catch(Exception)
{
return 1;
}
}
},
Reps = g.Sum(row => Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[2].Value)。
百分比 = (g.Sum(row => Convert.ToDecimal(row.Cells[2] .Value)) / Convert.ToDecimal(label15.Text)) * 100 //MessageBox.Show("Formato non corretto");
}
這將確保所有的行都被保留,但只有有效的行被計算在內。
一個更簡單的方法,不會保留原來的行數,就是檢查單元格的值是否是一個int或者可以轉換為一個int,就是添加下面的Where陳述句:
Where(row => row.Cells[2] 。 Value is int || int. TryParse((row.Cells[2].Value as string),out var result)
注意,你實際上是在決議每個迭代中的值,并丟棄結果,這當然遠遠沒有被優化,但會得到你想要的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310094.html
標籤:
