![](/img/trans.png)
[英]How to get the value of a selected item in a combobox in a datagridview
[英]How to get the TEXT of Datagridview Combobox selected item?
如何獲取DataGridView內的組合框選定項文本? 我嘗試使用以下代碼:
dataGridView1.Rows[1].Cells[1].Value.ToString()
但是,這給出了與此單元格關聯的值,而不是組合框選定項文本。 我也試過這個:
DataGridViewComboBoxCell cell = dataGridView1[1,1] as DataGridViewComboBoxCell;
string value = cell.Value.ToString();
但是,這也沒有幫助。
我會很感激你的幫助。 提前致謝!
編輯:
假設我們有一個組合框,文本為No
和Yes
,值分別為 0 和 1。 當組合框更改時,我想在這里得到文本Yes
或No
。 但我得到的是使用上述代碼的值 0/1。 希望這能讓事情變得清楚。
更新:
好的,所以我一直在研究這個問題,經過大量努力並在我的同事的幫助下,我已經能夠解決問題並獲得所需的解決方案:
這是解決方案:
string SelectedText = Convert.ToString(dataGridView1.Rows[0].Cells[1].FormattedValue.ToString());
要在 DataGridView 中獲取組合框的選定值和選定文本,請嘗試以下代碼
string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());
int SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);
我設法以這種方式從單元格中提取該字符串值:
DataGridViewComboBoxCell dgvcmbcell = dataGridView1[1, 0] as DataGridViewComboBoxCell;
String text = dgvcmbcell.EditedFormattedValue.ToString();
解決這個問題的最簡單方法是使用調試器並查看 dgvcmdcell 對象。 在此您將找到可擴展節點“base”。 展開它並瀏覽它,您將找到所需的任何信息。
要訪問 datagridview 中當前選定的文本,您需要引用 Combobox 列的CurrencyManager 。 CurrencyManager與金錢無關,而是管理列與其數據源之間的綁定。 CurrencyManager可以告訴您組合框的當前選擇是什么。
代碼:
CurrencyManager cm = (CurrencyManager)DataGridView1.BindingContext[((System.Windows.Forms.DataGridViewComboBoxColumn)DataGridView1.Columns[0]).DataSource];
注意:沒有必要將列轉換為組合框,我只是這樣做是為了向您顯示我傳入的列。我使用索引 0 但使用任何索引是組合框列的實際索引。
現在使用貨幣管理器,您可以訪問該列的數據網格的當前選擇(因為這是您傳入的列)。
cm.Current; //returns the current selection whatever that is
所以在我的例子中,組合框列的數據源是一個名為 Choice 的類,choice 如下所示:
public class Choice
{
public string Text
{
get;
set;
}
}
當我訪問 cm.Current 屬性時,它將返回選擇類的一個實例,我現在可以訪問我的選擇類的Text屬性以查看選擇了什么值。 顯然,您必須根據您的特定情況進行調整。 我希望這有幫助。
也試試這個:
DataGridView.CurrentRow.Cells(Column.name).EditedFormattedValue.ToString()
EditedFormattedValue
對象在DataGridView
給出單元格的當前格式化值,無論單元格是被編輯還是處於編輯模式。 在DataGridView
捕獲ComboBox
選擇或任何單元格值更方便。
你可以試試這個:-
dataGridView1.CurrentRow.Cells[0].Value.ToString();
索引您需要查看的單元格的列,以您的ComboBoxColumn
的索引為准。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.