The DataGridView style in C

  • 2020-12-22 17:45:26
  • OfStack

This article gives an example of the DataGridView style in C#. Share to everybody for everybody reference. The details are as follows:

1. Set the color of alternate grid rows

public static void SetGridAlternatingRows(DataGridView dg)
{
    if (dg != null)
    {
 dg.RowsDefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
 dg.AlternatingRowsDefaultCellStyle.BackColor = Color.Wheat;
    }
}

2. Check the validity of cell content

private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
 dgv.Rows[e.RowIndex].ErrorText = "";
 if (!IsNumberic(e.FormattedValue.ToString()))   // validation
 {
     dgv.Rows[e.RowIndex].ErrorText = " This column can only be entered numerically ";
     dgv.CancelEdit();
 }
}

3. Cell selection mode

public static void FullRowSelectMode(DataGridView dg)
{
    try
    {
 if(dg != null)
     dg.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }
    catch { }
}

4. Set the appropriate column width

dg.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//for (int i = 0; i < dg.Columns.Count; i++)
//{
//    int bestWidth = dg.Columns[i].GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, false);
//    dg.Columns[i].MinimumWidth = bestWidth;
//    //dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
//    dg.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
//}

Hopefully this article has helped you with your C# programming.


Related articles: