Skip to content

Instantly share code, notes, and snippets.

@lucasloss
Created December 19, 2019 22:18
Show Gist options
  • Save lucasloss/9ed42c7d1244fdae71b75e6a8ea95685 to your computer and use it in GitHub Desktop.
Save lucasloss/9ed42c7d1244fdae71b75e6a8ea95685 to your computer and use it in GitHub Desktop.
System.Windows.Forms.DataGridView extension methods.
using System;
using System.Reflection;
using System.Windows.Forms;
namespace ExtensionMethods
{
/// <summary>
/// <see cref="DataGridView"/> extension methods.
/// </summary>
public static class DataGridViewExtensions
{
/// <summary>
/// Set the visibility of all columns of a DataGridView.
/// </summary>
/// <param name="dataGridView">The <see cref="DataGridView"/>.</param>
/// <param name="value">A <see cref="bool"/> value that indicates whether the columns should be visible.</param>
public static void SetColumnsVisibility(this DataGridView dataGridView, bool value)
{
if (dataGridView == null)
{
throw new ArgumentNullException(nameof(dataGridView));
}
foreach (DataGridViewColumn column in dataGridView.Columns)
{
column.Visible = value;
}
}
/// <summary>
/// Selects a row in the DataGridView.
/// </summary>
/// <param name="dataGridView">The <see cref="DataGridView"/>.</param>
/// <param name="rowIndex">The index of the row to be selected.</param>
public static void SelectRow(this DataGridView dataGridView, int rowIndex)
{
if (dataGridView == null)
{
throw new ArgumentNullException(nameof(dataGridView));
}
if (dataGridView.Rows.Count == 0)
{
return;
}
if (rowIndex < 0 || rowIndex > dataGridView.Rows.Count - 1)
{
return;
}
int visibleColumnIndex = dataGridView.GetFirstVisibleColumnIndex();
if (visibleColumnIndex != -1)
{
dataGridView.Rows[rowIndex].Selected = true;
dataGridView.CurrentCell = dataGridView.Rows[rowIndex].Cells[visibleColumnIndex];
}
}
/// <summary>
/// Gets the index of the first visible column.
/// </summary>
/// <param name="dataGridView">The <see cref="DataGridView"/>.</param>
/// <returns>
/// The index of the first visible column. Returns -1 if the <see cref="DataGridView"/> has no columns or no visible columns.
/// </returns>
public static int GetFirstVisibleColumnIndex(this DataGridView dataGridView)
{
if (dataGridView == null)
{
throw new ArgumentNullException(nameof(dataGridView));
}
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
if (dataGridView.Columns[i].Visible)
{
return i;
}
}
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment