簡體   English   中英

如何從使用數據表創建的組合框中獲取所選項目

[英]How do i get selected item from combobox which was created with datatable

在我的項目中,組合框值出現在一個名為“getArticles”的方法中。 這是方法:

public void getArticles(ComboBox cb)
{
    var getAll = getAllFromDB("articles", "", "articleName ASC");
    DataTable dt = getAll.Tables["articles"];
    cb.DataSource = dt;
    cb.DisplayMember = "articleName";
    cb.ValueMember = "id";
}

“getAllFromDB”方法正在從articles表中進行選擇並返回DataSet。 現在我的問題在這里。 當我使用cb.SelectedValue我可以獲得文章名稱的id值。 這很好,很好。 但是,當我使用cb.SelectedItem它顯示“System.Data.DataRowView”。
請問你能幫幫我,我怎么能得到像使用cb.selectedItem這樣的文章名稱?
親切的問候。

嘗試以下代碼行,可能有助於獲取所選項目。

        ComboBoxItem requiredItem = (ComboBoxItem)cboType.SelectedItem;
        string value = requiredItem.Content.ToString();

編輯:

抱歉,上面的ComboBoxItem僅適用於.Net Framework 4.5,它位於System.Windows.Controls命名空間中。 請參閱以下代碼部分以獲取答案並進行檢查

        DataTable dtable = (DataTable)comboBox1.DataSource;
        label1.Text = dtable.Rows[comboBox1.SelectedIndex][0].ToString();//gives you article id
        label2.Text = dtable.Rows[comboBox1.SelectedIndex][1].ToString();//gives you article name

暫無
暫無

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

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