Ayman Ayman - 5 months ago 43
C# Question

Hide datagridview column but still access it value

The below code is using the column that i want to be not visible which is [0]

dgpay.DataSource = p.AllData();
for (int i = 0; i < dgpay.Rows.Count; i++)
if (!dgpay.Rows[i].IsNewRow)
if (dgpay[0, i].Value.ToString() == txtpaymentid.Text)
dgpay.CurrentCell = dgpay.Rows[i].Cells[0];
dgpay.Rows[i].Selected = true;
dgpay.Rows[i].Selected = false;

When i tried to make
dgpay.Columns[0].Visible = false
the above code wont run probably.

How can i hide the column without affecting the code.


You hide the first column but then you tried to set current cell to a cell of first column. When you set current cell to an invisible cell you will receive an InvalidOperationException:

Current cell cannot be set to an invisible cell.

Just set the current cell using a visible column index, for example:

dgpay.CurrentCell = dgpay.Rows[i].Cells[1]; // I supposed Columns[1].Visible is true