Search code examples
c#wpfdatagridviewdatagrid

DataGrid with checkbox event


now consider i have this simple datagrid

enter image description here

here is my xaml

<DataGrid HorizontalAlignment="Left"
          Height="362"
          Margin="10,55,0,0"
          VerticalAlignment="Top"
          Width="362"
          x:Name="table">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn />
    </DataGrid.Columns>
</DataGrid>

code that fire this info

        MySqlCommand cmd = m.getmodel("select * from "+equip+" where stored="+place);
        MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);
        DataTable data = new DataTable(equip);
        dataAdapter.Fill(data);
        table.ItemsSource = data.DefaultView;

now here is the point , whenever i click this checkbox on the left , i need to send the imei code of same row to c# code , i need to store the imei of checked rows , any idea ?


Solution

  • When you add a DataColumn of type bool to the DataTable, the DataGrid will automatically generate a DataGridCheckBoxColumn, which is linked to the DataTable.

    private void InitializeDataTable()
    {
      MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);
    
      DataTable data = new DataTable(equip);
      dataAdapter.Fill(data);
    
      var checkBoxColumn = new DataColumn("Select", typeof(bool));
      data.Columns.Add(checkBoxColumn);
      checkBoxColumn.SetOrdinal(0); // Move column to the beginning
    
      foreach (DataRow row in data)
      {
        row["Select"] = false;
      }
    
      table.ItemsSource = data.DefaultView;
    
      data.ColumnChanged += OnColumnChanged;
    }
    
    private void OnColumnChanged(object sender, DataColumnChangeEventArgs e)
    {
      var imei = e.Row["imei"];
    }