DataGridView read only cells

前端 未结 9 431
余生分开走
余生分开走 2020-12-09 10:57

I have a binded DataGridView that contains a large amount of data. The problem is that some cells has to be ReadOnly and also when the user navigates with TAB or ENTER betwe

相关标签:
9条回答
  • 2020-12-09 11:22

    You can do this using the BeginningEdit event to check if the check if the cell meets a condition and cancel the operation if not:

    In the example below, if the cell already contains a value it will cancel the operation, deeming it as read only.

    xaml:

    <DataGrid BeginningEdit="DataGrid_BeginningEdit" ItemsSource="{Binding Example, Mode=TwoWay}"/>
    

    c#:

    private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        string content = (e.EditingEventArgs.Source as TextBlock).Text;
    
        if (!(String.IsNullOrEmpty(content)))
            e.Cancel = true;
    }
    
    0 讨论(0)
  • 2020-12-09 11:29

    Try to make the column rather than individual cells readonly before binding the data:

    this.dgrid.Columns["colName"].ReadOnly = true;
    

    If you need to do for individual cells within the column, then you will have to loop and set them like this:

    this.dgridvwMain.Rows[index].Cells["colName"].ReadOnly = true;
    
    0 讨论(0)
  • 2020-12-09 11:29

    You can use CellBeginEdit event and set e.Cancel = True when you need disable the cell.

    Private Sub DataGridView_CellBeginEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridViewMsg.CellBeginEdit
        If DataGridViewMsg.Rows(e.RowIndex).Cells("disable").Value = "Y" Then
            e.Cancel = True
        End If
    End Sub
    
    0 讨论(0)
  • 2020-12-09 11:33

    Once the column is read only (see Rashmi's response) you can handle this event...

    private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Tab)
        {
            Boolean readOnly = (sender as DataGridView).SelectedCells[0].ReadOnly;
    
            return;
        }
    
    }
    

    Which will get the next cell's read only property.

    Thanks

    0 讨论(0)
  • 2020-12-09 11:37
    this.dataGridViewEmpList.EditMode = DataGridViewEditMode.EditProgrammatically;
    
    0 讨论(0)
  • 2020-12-09 11:37

    There's a very nice sample here:
    http://blogs.msdn.com/netcfteam/archive/2006/04/25/583542.aspx

    You just need to override Paint() , I've used this on compact framework to change the backcolor depending on the cell contents so on the same note you shouldn't have any problem to set them read only.

    0 讨论(0)
提交回复
热议问题