2012-10-15 89 views
0

我試圖做這個錯誤specified cast is not validautocomplete對於datagridviewtextboxcell ..我附上了代碼快照以及stack trace。我在這裏錯過了什麼?在DataGridView Winform中進行文本框自動完成時出錯

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     TextBox prodCode = e.Control as TextBox; 
     if (dataGridView1.CurrentCell.ColumnIndex == 0) 
     { 
      var source = new AutoCompleteStringCollection(); 
      String[] stringArray = newDB.CustomerTbls.Where(s => s.Status == "Active" & s.Type == "Customer").Select(s => s.Name).ToArray<string>(); 
      source.AddRange(stringArray); 

      if (prodCode != null) 
      { 
       prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend; 
       prodCode.AutoCompleteCustomSource = source; 
       prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource; 

      } 
     } 
     else 
      prodCode.AutoCompleteCustomSource = null; 
    } 

DataGridView textbox cell autocomplete code

Stack trace

+1

你的問題類似於這個http://stackoverflow.com/q/7225290/122005。你有沒有嘗試移動控件實例TextBox prodCode = e.Control作爲TextBox;在if條件中,在檢查之前它不是null? – chridam

+0

@chridam:代碼與您指定的鏈接相同。我試着移動控件實例TextBox prodCode = e.Control作爲TextBox;在if條件內,但它仍然給出相同的錯誤。任何其他的消化? –

回答

1

我自己想出了這個問題。我試圖做的形式Datagridview AutocompleteChild Form。我上面發佈的代碼是new Form。所以我打開Child Form作爲一個新的Thread並試圖運行代碼,它的工作!感謝所有幫助@chridam。

+0

@chridam yup :) –

1

正如在此線程Problem faced in AutoComplete code for TextBox建議通過decyclone,在一個新的解決方案創建一個新的Windows應用程序項目,創建一個新的形式和嘗試下面的代碼與形式,即創建DataTable行數的大小的String[],然後將其添加到AutoCompleteStringCollection對象

AutoCompleteStringCollection data = new AutoCompleteStringCollection(); 
data.AddRange(new string[] 
    { 
     "January", 
     "February", 
     "March", 
     "April", 
     "May", 
     "June", 
     "July", 
     "August", 
     "September", 
     "October", 
     "November", 
     "December" 
    }); 

// Create and initialize the text box 
var prodCode = new TextBox 
{ 
    AutoCompleteCustomSource = data, 
    AutoCompleteMode = AutoCompleteMode.SuggestAppend, 
    AutoCompleteSource = AutoCompleteSource.CustomSource, 
    Location = new Point(20, 20), 
    Width = ClientRectangle.Width - 40, 
    Visible = true 
}; 

看看它是否有效。如果它不起作用,那麼您可以嘗試一種替代解決方案,如AutoCompleteCustomSource – Specified Cast is Not Valid中所述,即用ComboBox代替TextBox,並將其DropDownStyle設置爲DropDown