Ayman
Ayman

Reputation: 99

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]

LoadData();
MessageBox.Show(p.AddNew());
dgpay.DataSource = p.AllData();
p.Move2Last();
ShowData();
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;
        }
        else
        {
            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.

Upvotes: 1

Views: 249

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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

Upvotes: 1

Related Questions