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

时间:2017-11-01 13:33:11

标签: c# datagridview cell

我有一个包含两个或更多电话号码的单元格,用分号分隔。我需要单元格内的每个电话都能实现点击的特定操作。例如:如果我点击特定号码,它将显示一个带有此号码的消息框。

1 个答案:

答案 0 :(得分:0)

使用Master / Details的方法。拆分电话列表并将其存储在字符串集合中。将此集合绑定到合适的控件,例如ListBox。处理此控件中的选择更改。

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; }
    }
}