How to select a row inside a datagridview cell?

后端 未结 2 380
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 08:12

Dear users: I have a datagridview that im using in a windows form with c sharp, this datagridview has columns as follows:

  • name
  • price
  • detail<
2条回答
  •  时光说笑
    2021-01-14 08:35

    Posting this answer because the OP requested it.

    This is how you would do that in WPF:

    
        
            

    Code Behind:

    public partial class ListBoxInCell : Window
    {
        public ViewModel ViewModel { get; set; }
    
        public ListBoxInCell()
        {
            InitializeComponent();
    
            DataContext = ViewModel = new ViewModel();
        }
    
        private void ShowDetail(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(ViewModel.SelectedItem.SelectedDetail);
        }
    }
    

    ViewModel:

    public class ViewModel
    {
        public List Items { get; set; }
    
        public Data SelectedItem { get; set; }
    
        public ViewModel()
        {
            //Sample Data
            Items = Enumerable.Range(0, 100).Select(x => new Data
                {
                    Product = "Product" + x.ToString(),
                    Details = Enumerable.Range(0, 3)
                                        .Select(d => "Detail" + x.ToString() + "-" + d.ToString())
                                        .ToList()
                }).ToList();
            SelectedItem = Items.First();
        }
    }
    

    Data Item:

    public class Data
    {
        public string Product { get; set; }
    
        public List Details { get; set; } 
    
        public string SelectedDetail { get; set; }
    }
    

    Result:

    enter image description here

    • MVVM, which means data is separate from UI and UI is separate from data.
    • No "owner draw", no "P/Invoke" (whatever that means), and no horrible procedural hacks. Only beautiful XAML and DataBinding.
    • The selection of each ListBox inside each row is indiviual, you may want to keep only 1 selected Item by setting all the others to null with a simple LINQ query and an iteration.
    • click on the button to see the currently selected Detail for the currently selected Row in the ListView.
    • WPF Rocks, copy and paste my code in a File -> New Project -> WPF Application and see the results for yourself.
    • Forget winforms. It's useless. It doesn't support any level of customization and requires a lot of horrible hacks for everything. It doesn't support (real) DataBinding and forces you into a boring procedural approach.

提交回复
热议问题