首页 > 解决方案 > Making One Column of DataGridView AutoComplete for String Data

问题描述

I am trying to set up a DataGridView in VB.Net where a single column, called "Supplier" acts as a TextBox with an AutoCompleteSource to help users with entering data. This is the code I put together to attempt to accomplish this:

Private Sub OrderData_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles orderData.EditingControlShowing
    Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex
    Dim headerText As String = orderData.Columns(colIndex).HeaderText
    If headerText.Equals("Supplier") Then
        Dim autoText As TextBox = TryCast(e.Control, TextBox)
        If autoText IsNot Nothing Then
            autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
            autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
            autoText.AutoCompleteCustomSource = FillTextBoxData("supplier_name", "suppliers")
        End If
    End If
End Sub

I kind of works. Unfortunately it adds AutoCompletes to every single editable column in the table, instead of just the "Supplier" column (column index 2).

What do I need to do to fix this?

EDIT: I modified the code a bit to try and fix the issue, and it kind of worked. If I don't selected the "Supplier" column first, then the other columns to not contain an AutoComplete. However if I go from the "Supplier" column to another column, then it contains an AutoComplete. How do I fix this?

标签: vb.netdatagridviewautocomplete

解决方案


当你这样做

Dim headerText As String = orderData.Columns(2).HeaderText
If headerText.Equals("Supplier") Then

这将永远是正确的,因为无论选择什么单元格,你总是得到 col 2 标题,你需要添加它,比如

Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex

然后你可以使用你的代码

Dim headerText As String = orderData.Columns(colIndex).HeaderText

还要在语句中添加一个Else子句If headerText.Equals("Supplier") Then。在该Else部分添加行autoText.AutoCompleteMode = AutoCompleteMode.None


推荐阅读