简体   繁体   中英

Catch ColumnWidthChanged event except data source updated for DataGridView

The data source of my dataGridView (grdBandControl) is updated every seconds.

Each time it is updated, grdBandControl_ColumnWidthChanged is fired.

I want to resize columns manually by resizing column header visually and store in a relevant variable.

How can I distinguish grdBandControl_ColumnWidthChanged is fired either:

  • Datasource updated
  • Resized visually

Codes are as below as it can give idea:

class ColumnNameWidth
{
    public string ColumnName { get; set; }
    public int ColumnWidth { get; set; }
}
List<ColumnNameWidth> ColumnNameWidths = new List<ColumnNameWidth>();

void grdBandControl_DataSourceUpdate()
{
    //some dataTable from Db i.e.
    grdBandControl.DataSource = dataTable;
    foreach (var columnNameWidth in ColumnNameWidths)
    {
        grdBandControl.Columns[columnNameWidth.ColumnName].Width = columnNameWidth.ColumnWidth;
    }
}

private void grdBandControl_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
    foreach (DataGridViewColumn col in grdBandControl.Columns)
    {
        var columnNameWidth = ColumnNameWidths.FirstOrDefault(x => x.ColumnName == col.Name);
        if (columnNameWidth != null)
            columnNameWidth.ColumnWidth = col.Width;
        else
            ColumnNameWidths.Add(new ColumnNameWidth
            {
                ColumnName = col.Name,
                ColumnWidth = col.Width
            });
    }
}

So after digging some, I figure out using grdBandControl_MouseUp instead of grdBandControl_ColumnWidthChanged solves issue.

private void grdBandControl_MouseUp(object sender, MouseEventArgs e)
{
    foreach (DataGridViewColumn col in grdBandControl.Columns)
    {
        var columnNameWidth = ColumnNameWidths.FirstOrDefault(x => x.ColumnName == col.Name);
        if (columnNameWidth != null)
            columnNameWidth.ColumnWidth = col.Width;
        else
            ColumnNameWidths.Add(new ColumnNameWidth
            {
                ColumnName = col.Name,
                ColumnWidth = col.Width
            });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM