Reputation: 1
I am programming in C#. The program is about rows for a student associated with. I have list of student names and I am going to use only one student iD and print all of its grades in Data grid View. I am not able to do that and it's just showing me all student grades. All I need is printing specifically only grades of a student.
private BindingList<StudentGrade> _studentGrade = new BindingList<StudentGrade>();
public frmGrades(int studentID)
{
InitializeComponent();
loadItemsFromFiles();
dgvGrades.DataSource = _studentGrade;
string id = studentID.ToString();
for (int z = 0; z < dgvGrades.Rows.Count;z++)
{
if (!dgvGrades.Rows[z].Cells["StudentID"].Value.ToString().Equals(id))
{
dgvGrades.Rows.RemoveAt(z);
z--;
dgvGrades.Refresh();
}
}
}
Upvotes: 0
Views: 324
Reputation: 125227
You don't need to remove elements from grid or list. In such cases you can use filtering. You can filter input list using linq and set filtered result as DataSource
of DataGridView
:
var filteredBindingList = new BindingList<StudentGrade>(
_studentGrade.Where(x => x.StudentID == studentID).ToList());
dgvGrades.DataSource = filteredBindingList;
Upvotes: 1
Reputation: 29026
It is not allowed to modify the collection while iterating the same; what you can do is delete the rows from the binding source and bind it again: ie.,
// collecting rows that satisfies the condition
var query = _studentGrade.AsEnumerable().Where(row => row.Field<string>("StudentID") == id );
//deleting collected rows from the source
foreach(var row in query.ToList())
row.Delete();
// re assign the datasource
dgvGrades.DataSource = _studentGrade;
dgvGrades.Refresh();
Upvotes: 1