Click here to Skip to main content
15,924,193 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am having a problem with setting the property of a particular cell of DataGridView to read-only. I am binding a DataGridView "dgv" to a DataSet (DataSet retrieved from a stored procedure) and then setting the properties of dgv columns for e.g. color, font, allignment etc and it is working fine. Now I want some particular cells of dgv to be read-only, but it is not working. I've tried a lot of things for e.g.

dgv.Item(0, 1).ReadOnly = True

OR

dgv.Rows(0).Cells(1).ReadOnly = True


Any help will be greatly appreciated.
Posted

Simply,

use rowdatabound event of gridview
and write

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.row.cells[6].enabled=false;
} :-O
 
Share this answer
 
I have a similar question up here, but a thought has struck me which I must try.

Putting a conditional check in the cell begin edit, and if true, set your cells readonly then leave the CellBeginEdit event.

<pre lang="cs">if(Set_some_cells_readonly && (e.ColumnIndex == 0
    || e.ColumnIndex == 1
    || e.ColumnIndex == 2))
{
    // The cells must be set readonly otherwise edit proceeds as normal
    // even with an e.cancel - all that does is kill the begin process
    dgv.Rows[e.RowIndex].Cells[0].ReadOnly = true;
    dgv.Rows[e.RowIndex].Cells[1].ReadOnly = true;
    dgv.Rows[e.RowIndex].Cells[2].ReadOnly = true;
    dgv.CurrentCell.Selected = false;
    // It is not enough to end the edit, we must leave the cell otherwise
    // it remains in write mode for this turn and only becomes readonly
    // after this edit event ends.
    dgv.CurrentCell = nullptr;
    return; // just in case any other code 'slips in' at a later date
}
else
    {
        dgv.Rows[e.RowIndex].Cells[0].ReadOnly = false;
        dgv.Rows[e.RowIndex].Cells[1].ReadOnly = false;
        dgv.Rows[e.RowIndex].Cells[2].ReadOnly = false;
    }


 
Share this answer
 
v2
Sorry, I am unable to find any RowDataBound Event of DataGridView or something like that.
 
Share this answer
 
You can use the CellBeginEdit and UserDeletingRow events

Cancel Editing
VB
Private Sub dgv_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgv.CellBeginEdit

 If e.RowIndex = 0 And e.ColumnIndex = 1 Then
    e.Cancel = True
 End If

End Sub


Cancel Deleting
VB
Private Sub dgv_UserDeletingRow(sender As Object, e As DataGridViewRowCancelEventArgs) Handles dgv.UserDeletingRow
    e.Cancel = True
End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900