简体   繁体   English

在c#中的datagridview中拆分单元格内容

[英]Split Cell content in datagridview in c#

I have a cell with two or more phone numbers split by a semicolon.我有一个单元格,其中有两个或多个电话号码,用分号分隔。 I need that each telephone inside the cell realize a especific action on click.我需要单元格内的每部电话都能在点击时实现特定的操作。 Exemple: if I click in especific number it will show a message box with this number.例如:如果我单击特定号码,它将显示一个带有此号码的消息框。

Use the approach of Master/Details.使用 Master/Details 的方法。 Split the phone list and store it in the string collection.拆分电话列表并将其存储在字符串集合中。 Bind this collection to a suitable control such as a ListBox .将此集合绑定到合适的控件,例如ListBox Handle the selection change in this control.处理此控件中的选择更改。

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        DataGridView peopleDataGridView;
        ListBox phonesListBox;
        List<Person> people;

        public Form1()
        {
            //InitializeComponent();

            peopleDataGridView = new DataGridView { Parent = this, Dock = DockStyle.Top };
            phonesListBox = new ListBox { Parent = this, Dock = DockStyle.Bottom };

            people = new List<Person> {
                new Person { Id=1, Name="John", Phones=new List<string> { "123", "456" } },
                new Person { Id=2, Name="Smit", Phones=new List<string> { "789", "012" } }
            };

            var peopleBindingSource = new BindingSource();
            peopleBindingSource.DataSource = people;
            peopleDataGridView.DataSource = peopleBindingSource;

            var phonesBindingSource = new BindingSource(peopleBindingSource, "Phones");
            phonesListBox.DataSource = phonesBindingSource;

            phonesListBox.SelectedIndexChanged += PhonesListBox_SelectedIndexChanged;
        }

        private void PhonesListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(phonesListBox.SelectedItem.ToString());
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<string> Phones { get; set; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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