How to change text of a Datagridview Button Cell on every update of Datasource

1.3k Views Asked by At

i have a c# application which recieves a packet from TCP and while parsing the packet i create a button column in the datagridview. The text of the button needs to be changed according to the received data i.e if '0' is received, the button text for that row must be 'STOP' and if '1' is received, the button text for that row must be 'START'. There are always multiples rows. The data source of the Datagridview updates every 10 seconds.

 if (port_dict[kvp.Key] == "0")
{
           PORT_BUTTON_DICT[kvp.Key].UseColumnTextForButtonValue = true;
           PORT_BUTTON_DICT[kvp.Key].Text = "START";
           this.Invoke(new Action(() =>datagridPM[datagridPM.Columns.Count - 1, row_count].ReadOnly=false));
           this.Invoke(new Action(() => datagridPM[datagridPM.Columns.Count - 1, row_count].Value = PORT_BUTTON_DICT[kvp.Key]));
           this.Invoke(new Action(() => datagridPM[datagridPM.Columns.Count - 1, row_count].ReadOnly = true));
           this.Invoke(new Action(() => datagridPM.Rows[row_count].Cells[datagridPM.Columns.Count - 1].Value = PORT_BUTTON_DICT[kvp.Key].Text));

 }

 else
 {
           PORT_BUTTON_DICT[kvp.Key].UseColumnTextForButtonValue = true;
           PORT_BUTTON_DICT[kvp.Key].Text = "STOP";
           this.Invoke(new Action(() =>datagridPM[datagridPM.Columns.Count - 1, row_count].ReadOnly=false));
           this.Invoke(new Action(() => datagridPM[datagridPM.Columns.Count - 1, row_count].Value = PORT_BUTTON_DICT[kvp.Key]));
           this.Invoke(new Action(() => datagridPM[datagridPM.Columns.Count - 1, row_count].ReadOnly = true));
           this.Invoke(new Action(() => datagridPM.Rows[row_count].Cells[datagridPM.Columns.Count - 1].Value = PORT_BUTTON_DICT[kvp.Key].Text));
 }

What i am facing is every time text of all the buttons changes if any one changes. I want button texts only for those rows to change for which the value has changed, not for every row.

1

There are 1 best solutions below

3
On

Setting UseColumnTextForButtonValue property to true indicates that the value of the Text property is used as button value. If it is set to false then the value of the each cell is displayed on the button.

In your code it is set to true. So, whenever you change the Text property value all the rows are updated.

Remove the below line from your code as the default value of UseColumnTextForButtonValue is false.

PORT_BUTTON_DICT[kvp.Key].UseColumnTextForButtonValue = true;