繁体   English   中英

C#:如何在DataGridView中使用DataGridViewComboBoxColumn显示绑定数据

[英]C#: How to Display Binding Data with DataGridViewComboBoxColumn in DataGridView

我认为这不是一个难题。 但我只是找不到/用谷歌找到答案。 请帮忙。

基本上,我的应用程序可以帮助用户找到单词列表(从一堆文件中)以及包含这些单词的文件列表。

说我有:

public class WordInfo
{
    public string Word { get; set; }
    public List<string> Files { get; set; }
}

而且我还从List<WordInfo>创建了BindingList<WordInfo> List<WordInfo> ,并将BindingList<WordInfo>绑定为DataGridView.DataSource

我只是不知道如何在DataGridView使用DataGridViewComboBoxColumn显示WordInfo.Files

我在Google上搜索了很多,似乎必须设置:

DataGridViewComboBoxColumn cbxColumn = dgvWordList.Columns["Files"] as DataGridViewComboBoxColumn;
cbxColumn.DataSource = ??????; // How to get this data source from BindingList<WordInfo>
cbxColumn.DisplayMemeber = "DisplayMemeber"; // Can I have an example?
cbxColumn.ValueMember = "ValueMember"; // Can I have an example?

但是我不知道如何设置这些属性。 我用谷歌搜索,但是例子太复杂了。

请帮忙。 谢谢。

我认为我在理解DataGridViewComboBoxColumn遇到一些问题,并且MSDN文档使我发疯。

彼得

问题是我认为您不能只拥有一个单词的BindingList ...
您应该定义一个BindingList<WordInfo>并将Word属性绑定到数据网格的Word列。 那么您应该在RowEnter或当前行更改时的某处编写一些代码,以便将Files列表绑定到该DataGridViewComboBoxColumn 这就是我所做的:



WordInfoCollection ww;

private void Form1_Load(object sender, EventArgs e)
{
    ww = new WordInfoCollection();

    //After filling data to this variable, 
    //you should set it as a BindignSource DataSource property
    wordsBindingSource.DataSource = ww;
}

private void wordsBindingSource_CurrentChanged(object sender, EventArgs e)
{
    if (wordsBindingSource.Current == null) return;

    clFiles.DataSource = ww[wordsBindingSource.Position].Files;
}

那么您只需要将您的datagridview绑定到wordsBindingSource ...
祝好运

解决了!
最终我找到了答案...您不需要使用任何事件...只需在绑定form_Load代码后编写此代码(也许在form_Load

int x = 0;
foreach (WordInfo word in ww)
{
    DataGridViewComboBoxCell dgCell = ((DataGridViewComboBoxCell)dgvWordList.Rows[x++].Cells["clFiles"]);
    dgCell.Items.AddRange(word.Files.ToArray());
}

祝你好运,我的朋友 ;)

暂无
暂无

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

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