Is this good practise? I have 3 DataGridView's and I want to have a facility that allows a user to sort the data by clicking on a column header. I could've had an event handler for the ColumnHeaderMouseClick event for each of these DataGridView's, but instead I made one:
private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
SortDataGridView((sender as DataGridView), e.ColumnIndex);
}
SortDataGridView looks like this:
/// <summary>
/// Sorts a given DataGridView by a column given by its columnIndex.
/// Default sort (if it isn't currently sorted) is Ascending. If it's
/// already sorted Ascending, change it to Descending. If it is Descending,
/// change it to Ascending.
/// </summary>
/// <param name="dataGridViewToSort">The DataGridViewToSort</param>
/// <param name="columnIndexToSortBy">The index of the column which we want to sort by in the DataGridView.</param>
private void SortDataGridView(DataGridView dataGridViewToSort, int columnIndexToSortBy)
{
switch (dataGridViewToSort.SortOrder)
{
case SortOrder.Ascending:
dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Descending);
break;
case SortOrder.Descending:
dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Ascending);
break;
case SortOrder.None:
dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Ascending);
break;
default:
break;
}
}
Each of the DataGridView's ColumnHeaderMouseClick event is hooked up to this handler. This implies that in order to realise which one raised the event at runtime, I have to say (sender as DataGridView). Is this safe? Could sender ever be something that's not a DataGridView?