简体   繁体   中英

C# WPF DataGrid I can't edit cells (isReadyOnly false)

I have this DataGrid:

      <DataGrid x:Name="grid1" HorizontalAlignment="Left" Height="349" Margin="10,38,0,0" VerticalAlignment="Top" Width="772" IsReadOnly="False" IsManipulationEnabled="True"  SelectionMode="Single">
      </DataGrid>

And I load the data from an Access database file:

        ole = new OleDbConnection();
        ole.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ervin\source\repos\FeriCrm\FeriCrm\bin\Debug\data.accdb;Persist Security Info=False";
        ole.Open();
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "select * from [partner]";
        cmd.Connection = ole;
        OleDbDataReader rd = cmd.ExecuteReader();                      
        grid1.ItemsSource = rd; 

I see the database rows and columns properly but I cannot edit the cells. I tried manually set grid1.isReadOnly=false or even grid1.Columns[0].isReadOnly=false. Nothing helped. How can I enable cell editing?

Since the OleDbDataReader just deliver the data rows without holding any data fields to update, the generated columns have the IsReadOnly set to True. You need to read the data into an ObservableCollection of some kind of Partner class with properties for each field. You then bind the grid1.ItemsSource to the ObservableCollection.

Another simpler version in your case is to use a DataTable:

        OleDbDataReader rd = cmd.ExecuteReader();
        DataTable dataTable = new DataTable();
        dataTable.Load(rd);
        grid1.ItemsSource = dataTable.AsDataView();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM