簡體   English   中英

如何在數據綁定的DataGridViewComboBox中顯示屬性而不是值?

[英]How to display a property instead of the value in a databound DataGridViewComboBox?

我是C#和.NET的新手

我需要在數據綁定的DatagridViewComboBox中顯示值的匹配名稱,但是我不知道該怎么做。

我有以下代碼:

bs = new BindingSource();
bs.DataSource = typeof(CR);

dataGridView1.AutoGenerateColumns = false;
Column1.Width = 400;
Column1.DataPropertyName = "CR_NAME";
Column2.DataPropertyName = "CR_STATE_S";
Column2.ValueMember = "CR_STATE_S";
Column2.DisplayMember = "GetStateName";

Column2.Items.Add("0"); // how to set the matching value here?
Column2.Items.Add("1");
Column2.Items.Add("2");

dataGridView1.DataSource = bs;

GetStateName是CR類的屬性,該屬性返回CR狀態的匹配名稱。 我需要在組合框中顯示狀態名稱。 怎么做? 謝謝。

如果要顯示與單元格應包含的值不同的內容,則不能簡單地將一件事加載到ComboBoxCells的項中。

取而代之的是,您需要一個至少具有兩個不同字段的數據源:

  • 數據的可視表示形式的字段,稱為DisplayMember
  • 實際數據值的字段稱為ValueMember

這些字段可以位於DataTable但是您也可以使用具有適當屬性的任何其他集合。

讓我們創建一個非常簡單的類並具有該類的列表:

class itemClass
{
    public string display { get; set;}
    public string value { get; set; }
    public itemClass(string d, string v) 
    { display = d; value = v;}
}

List<itemClass> myItems = new List<itemClass>();

private void loadButton_Click(object sender, EventArgs e)
{
    // load the list with all values:
    myItems.Add(new itemClass("zero", "0"));
    myItems.Add(new itemClass("one", "1"));
    myItems.Add(new itemClass("two", "2"));
    myItems.Add(new itemClass("three", "3"));
    myItems.Add(new itemClass("four", "4"));
    myItems.Add(new itemClass("five", "5"));
    myItems.Add(new itemClass("six", "6"));

    // prepare the DataGridView 'DGV':
    DGV.Columns.Clear();
    DataGridViewComboBoxCell cCell = new DataGridViewComboBoxCell();

    DataGridViewComboBoxColumn cCol = new DataGridViewComboBoxColumn();
    DGV.Columns.Add(cCol);
    cCol.DisplayMember = "display";
    cCol.ValueMember = "value";
    cCol.DataSource = myItems;
    cCol.ValueType = typeof(string);

    // add a few rows, for testing:
    DGV.Rows.Add(7);
    for (int i = 0; i < DGV.Rows.Count; 
        i++) DGV.Rows[i].Cells[0].Value = i + "";
}

在示例中,我手動加載了Items 通常,您將需要從數據庫或其他來源中提取值。 您可以通過如上所述加載數據源列表來做到這一點,也可以獨立地或在DataSet擁有查找表。

如果所有單元格都需要具有單獨的查找值,則需要分別加載它們,而不使用列,而是將每個單元格強制轉換為DataGridViewComboBoxCell

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM