数据没有很好地添加到 ListView。 (C#window形式)

Data is not added well to ListView. (C# window form)

我添加了 3 列。

修改后的属性值如下

  1. 查看 - 详情
  2. 在线 - 正确
  3. 腰线 - 正确
  4. FullRowSelect - 真
namespace TestWinForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void add_Click(object sender, EventArgs e)
        {
            //listView1.BeginUpdate();
            string[] row = { "123", "456", "789" };
            ListViewItem list_view = new ListViewItem(row);
            listView1.Items.Add(list_view);
            textBox1.Text = listView1.Items.Count.ToString();
            //listView1.EndUpdate();
        }
    }
}

是每点击add按钮添加一个数据行后更新当前行数为textbox1的代码

很明显,行数一直在上升....但是数据没有输出到listView1.

我应该检查哪一部分?

很久没用过 Winforms,但我记得使用绑定源更可靠

var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;

//Add data to dataTable and then call

bindingSource.ResetBindings(false)  

您所拥有的应该在添加了列的详细视图中工作。这是一个例子

设计视图

在这种情况下,使用了以下 class 的实例,以便稍后我们可以获得有关特定行的信息。

public class Contact
{
    public int CustomerIdentifier { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneTypeDescription { get; set; }
    public string PhoneNumber { get; set; }
    public string CountryName { get; set; }
    public string[] ItemArray => new[]
    {
        CompanyName,
        FirstName,
        LastName,
        PhoneNumber,
        CountryName
    };
}

执行模拟添加的代码

private void AddRowButton_Click(object sender, EventArgs e)
{
    var companyName = "Just added";

    Contact contact = new Contact()
    {
        CompanyName = companyName,
        FirstName = "Karen",
        LastName = "Payne",
        PhoneNumber = "123-333-4444",
        CountryName = "USA"
    };

    ownerContactListView.Items.Add(
        new ListViewItem(contact.ItemArray)
        {
            Tag = contact.CustomerIdentifier
        });

    CountLabel.Text = $@"Row count: {ownerContactListView.Items.Count}";

    var index = ownerContactListView.Items.IndexOf(
        ownerContactListView.FindItemWithText(companyName));

    ownerContactListView.Items[index].Selected = true;
    ownerContactListView.EnsureVisible(index);
    ActiveControl = ownerContactListView;
}

添加上面的行后(注意我缩短了表格所以你看到的是局部视图)

您可以看到整个初始加载,请参阅 the following