Может C# BindingSource содержать массив строк - PullRequest
0 голосов
/ 27 апреля 2020

У меня очень простое приложение с DataGridView, для которого привязкаSource присвоена его свойству DataSource. bindingSource - это тип BindingSource, для которого данные назначены его свойству DataSource. Данные имеют только одно свойство 'string [] files'. Проблема в том, что при попытке выбрать столбцы для отображения с помощью Visual Designer «Выбранные столбцы» пустые. Почему? Я не могу прикрепить zip-файл крошечного проекта, созданного в Visual Studio 2017, поэтому я предоставляю код:

namespace WindowsFormsAppTest
{
  class Data
  {
    private string[] files;
    public string[] Files { get => files; set => files = value; }
  }
}

using System;
using System.Windows.Forms;

namespace WindowsFormsAppTest
{
partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false. 
    </param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
    #region "business object"

    #endregion

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.dataGridView = new System.Windows.Forms.DataGridView();
        this.bindingSource = new System.Windows.Forms.BindingSource(this.components);
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
        ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).BeginInit();
        this.SuspendLayout();
        // 
        // dataGridView
        // 
        this.dataGridView.AutoGenerateColumns = false;
        this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView.DataSource = this.bindingSource;
        this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
        this.dataGridView.Location = new System.Drawing.Point(0, 0);
        this.dataGridView.Name = "dataGridView";
        this.dataGridView.Size = new System.Drawing.Size(800, 450);
        this.dataGridView.TabIndex = 1;
        // 
        // bindingSource
        // 
        this.bindingSource.DataSource = typeof(WindowsFormsAppTest.Data);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Controls.Add(this.dataGridView);
        this.Name = "Form1";
        this.Text = "Form1";
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
        ((System.ComponentModel.ISupportInitialize)(this.bindingSource)).EndInit();
        this.ResumeLayout(false);

    }

    #endregion
    private DataGridView dataGridView;
    private BindingSource bindingSource;
}
}

С уважением,

Януш

1 Ответ

0 голосов
/ 27 апреля 2020

Чтобы привязать к представлению таблицы данных, источником данных должна быть коллекция:

public class Data : List<EclipseFileInfo> { }

public class EclipseFileInfo
{
    private List<string> files;
    private string alias;

    public List<string> Files { get { return files; } set { files = value; } }
    public string Alias { get { return alias; } set { alias = value; } }
}

Когда вы sh отобразите строку файлов [] в виде поля со списком в вашем представлении сетки, нам нужно вручную добавить поле со списком, а также вручную установить его источник данных. Мы можем выполнить первую часть в конструкторе формы:

public Form2()
{
    InitializeComponent();

    dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
    DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();

    dataGridView1.Columns.Add(comboboxColumn);

    Data data = new Data();
    data.Add(new EclipseFileInfo() { Alias = "Some Namespace 1", Files = new List<string> { "File1", "File2" } });
    data.Add(new EclipseFileInfo() { Alias = "Some Namespace 2", Files = new List<string> { "File3", "File4" } });
    data.Add(new EclipseFileInfo() { Alias = "Some Namespace 2", Files = new List<string> { "File5", "File6" } });

    dataGridView1.DataSource = data;
}

Затем вторая часть в обработчике события DataBindingComplete:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewComboBoxCell cell = row.Cells[1] as DataGridViewComboBoxCell;
        cell.DataSource = (row.DataBoundItem as EclipseFileInfo).Files;
    }
}

Окончательное представление выглядит следующим образом:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...