2013-12-10 91 views
-1

我在填充數據網格視圖中的comboxcolumn時遇到問題。這裏是我的問題的簡要描述。如何將項目添加到DataGridView ComboBoxColumn?

我有一個名爲dgvRightsColumn的datagrid視圖中的組合列和SQL中名爲Rights的表。我想用權利表中的RightsNames填充這個dagaridview的組合框。

DataGridViewComboBoxColumn dgvRightsColumn = new DataGridViewComboBoxColumn(); 

SqlCommand fillRights = new SqlCommand("SELECT * FROM [Rights]", sqlConnection); 
SqlDataReader readerRights = fillRights.ExecuteReader(); 

while (readerRights.Read()) 
{ 
    dgvRightsColumn.Items.Add(Convert.ToString(readerRights["RightName"])); 
} 

readerRights.Close(); 
+0

什麼是您所遇到的問題? – rae1

+0

它是winform嗎?或Webform? –

+0

感謝您回覆@ rae1n。此代碼不在組合框中添加項目。當我運行這個代碼。 Combobox仍然是空的 –

回答

2

問題:你只是創建對象DataGridViewComboBoxColumn但不能指定從GridView的視爲組合框是第3列的實際列。

解決方案:你需要從DataGridviewcast所需的列到DataGridViewComboBoxColumn插入項目。

替換此:

DataGridViewComboBoxColumn dgvRightsColumn = new DataGridViewComboBoxColumn(); 

這一點:

DataGridViewComboBoxColumn dgvRightsColumn= dgvTasksRights.Columns[2] as DataGridViewComboBoxColumn; 

注:你不執行ExecuteReader command.You之前打開SqlConnectoion對象sqlConnection需要打開它如下:

sqlConnection.Open(); 

完整代碼:
試試這個:

SqlCommand fillRights = new SqlCommand("SELECT * FROM [Rights]", sqlConnection); 
sqlConnection.Open(); 
SqlDataReader readerRights = fillRights.ExecuteReader(); 

DataGridViewComboBoxColumn dgvRightsColumn= dgvTasksRights.Columns[2] as DataGridViewComboBoxColumn; 
while (readerRights.Read()) 
{     
dgvRightsColumn.Items.Add(Convert.ToString(readerRights["RightName"])); 
} 
readerRights.Close(); 
+0

包的謝謝...我得到了我的錯誤。現在它正在工作。順便說一句,我剛剛發佈選定的代碼,我得到的問題SqlConnection已經打開:-p。再次感謝。 :-) –

+0

@AzeemKhalid:歡迎您:),我很高興能成爲您的幫助者。祝您有美好的一天。 –

+0

我可以和你聊聊...嗎? –