简体   繁体   中英

Showing a button column in a DataGridView

In a Win forms application I have a problem with data binding and showing a command button column in the DataGridView as the last column allowing users to save each records after editing the content.

This is the binding part done in the presenter class

private void ShowEarnings()
{
    BindingSource BS = new BindingSource();
    var wageInfo = _WageManager.PrepareEarnings(_Model); // wageInfo contains a list of earnings objects.
    BS.DataSource = wageInfo.GetEarnigsList(); //Earnings List contained in WageInfo object is returned.           
    _View.EarningDetails = BS;
}

In the form_load event I add a command button column to the DGV as follows

private void ShowSaveEarningsButton()
{
    DataGridViewButtonColumn col = new DataGridViewButtonColumn();
    col.UseColumnTextForButtonValue = true;
    col.Text = "SAVE";
    col.Name = "ACTION";
    dgEmployeeEarnings.Columns.Add(col);
}

When the form is loaded the last column is shown with the header ACTION and a blank button is shown in the cell (first screen shot). When the ShowEarnings() method is called, the DGV is populated and now the button column is shown as the 3rd column (second screen shot). But it should be shown as the last column always!.

How to sort this out please?

Please see the screen shots.

在此处输入图片说明

EDIT: if I add the column after the binding it is shown properly. But I want it first!

Subscribe the DataBindingComplete event and reset the DisplayIndex property.

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dgEmployeeEarnings.Columns["ACTION"].DisplayIndex = dgEmployeeEarnings.Columns.Count - 1;
}

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