You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中DataGridViewComboBoxCell是否有SelectedIndexChanged事件处理程序?

PowerShell处理DataGridView中ComboBoxCell的选择变化

DataGridView里的ComboBoxCell没有像独立ComboBox那样的add_selectedindexchanged()直接事件,但可以通过DataGridView的两个内置事件组合实现需求:

  • 先通过CurrentCellDirtyStateChanged事件提交ComboBox的选择修改,确保单元格值更新
  • 再通过CellValueChanged事件检查两个ComboBoxCell的选中索引,判断是否启用按钮

以下是完整实现代码:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 初始化窗体
$form = New-Object System.Windows.Forms.Form
$form.Text = "ComboBoxCell 状态检测"
$form.Size = New-Object System.Drawing.Size(400, 300)

# 创建DataGridView并添加ComboBox列
$dgv = New-Object System.Windows.Forms.DataGridView
$dgv.Dock = [System.Windows.Forms.DockStyle]::Top
$dgv.RowCount = 1
$dgv.ColumnCount = 2

# 第一列ComboBox
$comboCol1 = New-Object System.Windows.Forms.DataGridViewComboBoxColumn
$comboCol1.Name = "ComboColumn1"
$comboCol1.Items.AddRange("默认选项", "选项1", "选项2")
$dgv.Columns[0] = $comboCol1

# 第二列ComboBox
$comboCol2 = New-Object System.Windows.Forms.DataGridViewComboBoxColumn
$comboCol2.Name = "ComboColumn2"
$comboCol2.Items.AddRange("默认选项", "选项1", "选项2")
$dgv.Columns[1] = $comboCol2

# 创建目标按钮(默认禁用)
$targetBtn = New-Object System.Windows.Forms.Button
$targetBtn.Text = "执行操作"
$targetBtn.Dock = [System.Windows.Forms.DockStyle]::Bottom
$targetBtn.Enabled = $false

# 添加控件到窗体
$form.Controls.Add($dgv)
$form.Controls.Add($targetBtn)

# 处理ComboBox选择后的脏状态提交,确保值被更新到单元格
$dgv.add_CurrentCellDirtyStateChanged({
    if ($dgv.IsCurrentCellDirty -and $dgv.CurrentCell -is [System.Windows.Forms.DataGridViewComboBoxCell]) {
        $dgv.CommitEdit([System.Windows.Forms.DataGridViewDataErrorContexts]::Commit)
    }
})

# 检测单元格值变化,判断是否启用按钮
$dgv.add_CellValueChanged({
    # 获取两行ComboBox的选中索引
    $index1 = $dgv.Rows[0].Cells["ComboColumn1"].SelectedIndex
    $index2 = $dgv.Rows[0].Cells["ComboColumn2"].SelectedIndex

    # 当两个索引都大于0时启用按钮
    $targetBtn.Enabled = ($index1 -gt 0) -and ($index2 -gt 0)
})

# 显示窗体
$form.ShowDialog() | Out-Null

说明

  • CurrentCellDirtyStateChanged事件的作用是:当用户在ComboBoxCell中选择选项后,控件会标记为"脏状态",此时需要手动提交修改,否则CellValueChanged不会触发
  • 在CellValueChanged事件中,直接获取两个ComboBoxCell的SelectedIndex属性,判断是否都大于0,以此控制按钮的启用状态

内容的提问来源于stack exchange,提问作者Icoryx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:10:21