Change the text value of a button in DataGridViewButtonColumn

倖福魔咒の 提交于 2019-12-11 14:04:52

问题


I'm trying to change the text of a button in a DataGridViewButtonColumn every time the button is clicked.

I define the column like so:

DataGridViewButtonColumn sitemapButtonColumn = new DataGridViewButtonColumn
{
     Name = "Process",
     Text = "Start",
     UseColumnTextForButtonValue = true,
     DataPropertyName = "Process",
     FillWeight = 7,
     Width = 75
};
dg_list.CellContentClick += dg_list_StartStopProcessClick;

Now the function which controls the event once a cell clicked is:

private void dg_list_StartStopProcessClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
                e.RowIndex >= 0 &&
                e.ColumnIndex == dg_lista_blogs_automatizacion.Columns["Process"].Index)
            {
                if (senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "Start")
                {
                    senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Stop";
                    senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.OrangeRed;
                }
                else
                {
                    senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Start";
                    senderGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
                }
            }
        }

Well, this does not work!

I've been googling and found a post which modifies UseColumnTextForButtonValue to false, set the new text value and set to true again.

The problem is that i can not figure out how can i get access to UseColumnTextForButtonValue property within the event.

Any help?


回答1:


Basically, i could solve the problem setting UseColumnTextForButtonValue to false in the DataGridViewButtonColumn instance.

When UseColumnTextForButtonValue is set to false, the text value of the button must be initied in other event. So, i use CellFormatting event for setting the text value according to the state I desire.

private void dg_list_auto_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e!=null && e.ColumnIndex==0)
            {
                dg_list_auto.Rows[e.RowIndex].Cells[0].Value = dg_list_auto[e.RowIndex].flag_sitemap_started?"Stop":"Start";
                dg_list_auto.Rows[e.RowIndex].Cells[0].Style.BackColor = dg_list_auto[e.RowIndex].flag_sitemap_started ? Color.IndianRed: Color.GreenYellow;
            }
        }


来源:https://stackoverflow.com/questions/48430385/change-the-text-value-of-a-button-in-datagridviewbuttoncolumn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!