呈現出來的效果會是:
一開始 DataGrid 的欄位看起來是 DataGridTextBoxColumn (TextBox)
滑鼠點到該欄位時, 會自動變成下拉選單 (ComboBox)
當滑鼠點到其他欄位時, 欄位又會變回 DataGridTextBoxColumn
並將下拉選單中選定的文字顯示在 DataGridTextBoxColumn 上
Public Sub New()
MyBase.New()
InitializeComponent()
' 將 ComboBox 加入 DataGrid
BindComboBox()
End Sub
Private Sub BindComboBox()
Dim dt As New DataTable
Dim conn As New SqlClient.SqlConnection("連線字串")
Dim strSQL As String = "SQL敘述"
Dim cmd As New SqlClient.SqlCommand(strSQL, conn)
Dim adapter As New SqlClient.SqlDataAdapter(cmd)
conn.Open()
adapter.Fill(dt)
conn.Close()
' 要鑲入 ComboBox 的欄位必須是 DataGridTextBoxColumn
' GridColumnStyles(n) : n 代表要在第幾個 DataGridTextBoxColumn 鑲入, 0,1,2,...
Dim dgtbcCol As DataGridTextBoxColumn = DataGrid1.TableStyles(0).GridColumnStyles(2)
Dim cbCol As New ComboBox
' 將 ComboBox 的寬度設得和 DataGridTextBoxColumn 一樣寬
cbCol.width = 75
' 將 ComboBox onMouseOver 時的游標設為箭頭
cbCol.Cursor = Cursors.Arrow
' 將 ComboBox 的樣式設為下拉選單
cbCol.DropDownStyle = ComboBoxStyle.DropDownList
' 繫結 ComboBox 資料
cbCol.DataSource = dt
cbCol.ValueMember = "下拉值的欄位名稱"
cbCol.DisplayMember = "下拉文字的欄位名稱"
' 增加下拉選單值改變時的 Event
AddHandler cbCol.SelectionChangeCommited, AddressOf cbCol_SelectionChangeCommited
' 將 ComboBox 鑲入 DataGridTextBoxColumn 中
dgtbcCol.TextBox.Controls.Add(cbCol)
End Sub
Private Sub cbCol_SelectionChangeCommited(ByVal sender As Object, ByVal e As EventArgs)
' 將 ComboBox 選定的文字顯示在 DataGridTextBoxColumn 上
DataGrid1.Item(DataGrid1.CurrentCell) = Ctype(sender, ComboBox).Text
End Sub
MyBase.New()
InitializeComponent()
' 將 ComboBox 加入 DataGrid
BindComboBox()
End Sub
Private Sub BindComboBox()
Dim dt As New DataTable
Dim conn As New SqlClient.SqlConnection("連線字串")
Dim strSQL As String = "SQL敘述"
Dim cmd As New SqlClient.SqlCommand(strSQL, conn)
Dim adapter As New SqlClient.SqlDataAdapter(cmd)
conn.Open()
adapter.Fill(dt)
conn.Close()
' 要鑲入 ComboBox 的欄位必須是 DataGridTextBoxColumn
' GridColumnStyles(n) : n 代表要在第幾個 DataGridTextBoxColumn 鑲入, 0,1,2,...
Dim dgtbcCol As DataGridTextBoxColumn = DataGrid1.TableStyles(0).GridColumnStyles(2)
Dim cbCol As New ComboBox
' 將 ComboBox 的寬度設得和 DataGridTextBoxColumn 一樣寬
cbCol.width = 75
' 將 ComboBox onMouseOver 時的游標設為箭頭
cbCol.Cursor = Cursors.Arrow
' 將 ComboBox 的樣式設為下拉選單
cbCol.DropDownStyle = ComboBoxStyle.DropDownList
' 繫結 ComboBox 資料
cbCol.DataSource = dt
cbCol.ValueMember = "下拉值的欄位名稱"
cbCol.DisplayMember = "下拉文字的欄位名稱"
' 增加下拉選單值改變時的 Event
AddHandler cbCol.SelectionChangeCommited, AddressOf cbCol_SelectionChangeCommited
' 將 ComboBox 鑲入 DataGridTextBoxColumn 中
dgtbcCol.TextBox.Controls.Add(cbCol)
End Sub
Private Sub cbCol_SelectionChangeCommited(ByVal sender As Object, ByVal e As EventArgs)
' 將 ComboBox 選定的文字顯示在 DataGridTextBoxColumn 上
DataGrid1.Item(DataGrid1.CurrentCell) = Ctype(sender, ComboBox).Text
End Sub
要鑲入下拉選單的 DataGridTextBoxColumn 最好設為 ReadOnly
免得使用者不小心改掉欄位值
沒有留言:
張貼留言