簡體   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