一,ComboBoxColumn列的相关操作(动态绑定数据,SelelectedChanged事件)
界面效果图
- 给combox绑定数据(可以放在Page_Load中)
VB:
'repWiClient 数据源
CType(dgvBilling.Columns("ColRepNo"), DataGridViewComboBoxColumn).DataSource = (From t In repWiClient
Select t.ReportNo
).Concat({"--请选择--"}).Distinct().ToList()
2.DataGridViewComboBoxColumn 默认显示的下拉框,选择时需要点击三次,第一次选中单元格,第二次启用编辑,第三次打开下拉框。如果需要一次点击打开下拉框,可以启用DataGridView的CellEnter()事件,代码如下:
Private Sub dgvBilling_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBilling.CellEnter
'实现单击一次显示下拉列表框
If (TypeOf (dgvBilling.Columns(e.ColumnIndex)) Is DataGridViewComboBoxColumn And e.RowIndex <> -1) Then
SendKeys.Send("{F4}")
End If
End Sub
- 在DatagridView的EditingControlShowing事件中 绑定Combox的 SelectedIndexChanged 事件
Private Sub dgvBilling_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgvBilling.EditingControlShowing
If (dgvBilling.CurrentCell.OwningColumn.Name = "ColRepNo" And dgvBilling.CurrentCell.RowIndex <> -1) Then
' cbo = CType(e.Control, ComboBox)
AddHandler CType(e.Control, ComboBox).SelectedIndexChanged, AddressOf Me.ReportNo_SelectedIndexChanged
End If
End Sub
4.SelectedIndexChanged 事件
Private Sub ReportNo_SelectedIndexChanged(sender As Object, e As EventArgs)
'....执行的代码
'重要: 最后要撤销动态事件。如果不撤销,你在点击第二次时,会触发之前的事件,造成连续触发
RemoveHandler CType(sender, ComboBox).SelectedIndexChanged, AddressOf Me.ReportNo_SelectedIndexChanged
End Sub
二,加行的行号
RowStateChanged事件
private void dgvImport_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
}
三,某个列的单元格下拉日期控件输入,并加上右击菜单 清除单元格的日期
1.类文件,可以供多个页面共用
Imports System.Windows.Forms
Imports System.Windows.Forms.Control
Public Class DataGridViewHelper
#Region "show datetimepicker in the datagrid"
Dim dgv As DataGridView
Dim cellDateTimePicker As DateTimePicker
Dim rMenu As New ContextMenuStrip
Public Sub New()
End Sub
Public Sub New(ByVal pDgv As DataGridView, ByVal pRMenu As ContextMenuStrip, ByVal pCellDateTimePicker As DateTimePicker)
Me.dgv = pDgv
Me.rMenu = pRMenu
Me.cellDateTimePicker = pCellDateTimePicker
End Sub
' Dim cellDateTimePicker As DateTimePicker
Public Sub ShowDateTimePicker()
Try
Dim tempRect = dgv.GetCellDisplayRectangle(dgv.CurrentCell.ColumnIndex, dgv.CurrentCell.RowIndex, False)
cellDateTimePicker.Location = tempRect.Location
cellDateTimePicker.Width = tempRect.Width
cellDateTimePicker.Value = DateTime.Parse(dgv.CurrentCell.Value.ToString())
Catch ex As Exception
' cellDateTimePicker.Value = DateTime.Now.ToString("yyyy-MM-dd")
' dgv.CurrentCell.Value = cellDateTimePicker.Value
End Try
cellDateTimePicker.Visible = True
cellDateTimePicker.Focus()
End Sub
Public Sub cellDateTimePickerValueChanged(ByVal sender As Object, ByVal e As EventArgs)
dgv.CurrentCell.Value = cellDateTimePicker.Value.ToString("yyyy-MM-dd")
cellDateTimePicker.Visible = False
End Sub
Public Sub InitCellDateTimePicker()
'Init datetimePicker in datagridview
Me.cellDateTimePicker = New DateTimePicker()
Me.cellDateTimePicker.Visible = False
Me.cellDateTimePicker.CustomFormat = "yyyy-MM-dd"
Me.cellDateTimePicker.Format = DateTimePickerFormat.Custom
cellDateTimePicker.Value = DateTime.Now.ToString("yyyy-MM-dd")
dgv.Controls.Add(cellDateTimePicker)
AddHandler cellDateTimePicker.ValueChanged, AddressOf Me.cellDateTimePickerValueChanged
AddHandler cellDateTimePicker.Leave, AddressOf cellDateTimePicker_Leave
AddHandler cellDateTimePicker.MouseDown, AddressOf cellDateTimePicker_MouseDown
End Sub
Public Sub cellDateTimePicker_Leave(ByVal sender As Object, ByVal e As EventArgs)
Me.cellDateTimePicker.Visible = False
End Sub
#End Region
#Region "right click menu: set dbnull value of datetime "
Public Sub dgvPRing_CellMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)
If e.Button = System.Windows.Forms.MouseButtons.Right Then ' Right Then click
Dim curRow = dgv.Rows(e.RowIndex)
curRow.Selected = True
dgv.CurrentCell = curRow.Cells(e.ColumnIndex)
Dim colName = dgv.Columns(e.ColumnIndex).Name
'"CalDate", "DueDate" datagridview要显示日期控件的列名
If New String() {"CalDate", "DueDate"}.Contains(colName) Then
rMenu.Show(MousePosition.X, MousePosition.Y)
End If
End If
End Sub
Public Sub cellDateTimePicker_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If (e.Button = Windows.Forms.MouseButtons.Right) Then
rMenu.Show(MousePosition.X, MousePosition.Y)
End If
End Sub
Public Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
'NullDateToolStripMenuItem 右击菜单 清除日期的菜单项名称
If CType(sender, ContextMenuStrip).Items("NullDateToolStripMenuItem").Selected Then
dgv.CurrentCell.Value = DBNull.Value
cellDateTimePicker.Visible = False
End If
End Sub
#End Region
End Class
2. 调用的页面:
Dim dgvHelper As New DataGridViewHelper
Dim cellDateTimePicker As New DateTimePicker
'Form_Load事件
Private Sub frm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dgvVCA.AutoGenerateColumns = False
'Init DateTimePicker and right menu
dgvHelper = New DataGridViewHelper(dgvVCA, rMenu, cellDateTimePicker,New String() {"CalDate", "DueDate"})
dgvHelper.InitCellDateTimePicker()
AddHandler dgvVCA.CellMouseDown, AddressOf dgvHelper.dgvPRing_CellMouseDown
AddHandler rMenu.ItemClicked, AddressOf dgvHelper.ToolStripMenuItem_Click
End Sub
'show datetimepicker
Private Sub dgvPRing_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvPRing.CellEnter
Dim colName = dgvPRing.Columns(dgvPRing.CurrentCell.ColumnIndex).Name
If New String() {"CalDate", "DueDate"}.Contains(colName) Then
dgvHelper.ShowDateTimePicker()
Exit Sub
End If
End Sub
'cell input checking.
Private Sub dgvPRing_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvPRing.CellValidating
If e.FormattedValue Is Nothing Or e.FormattedValue.ToString().Length < 1 Then
Exit Sub
End If
Try
'check date
If (New String() {"CalDate", "DueDate"}.Contains(dgvPRing.Columns(e.ColumnIndex).Name)) Then
cellDateTimePicker.Visible = False
If Not IsDate(e.FormattedValue.ToString()) Then
e.Cancel = True
MsgBox("Error DateTime.")
End If
End If
Catch ex As Exception
e.Cancel = True
MessageBox.Show("Cell data checking error.")
End Try
End Sub
四,单元格只能输入数字
CellValidating 事件
VB.NET
Private Sub dgvPRing_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvPRing.CellValidating
If (New String() {"RowIndex", "EquipmentNo", "CalDate", "DueDate"}.Contains(dgvPRing.Columns(e.ColumnIndex).Name)) Then
Exit Sub
End If
If (e.FormattedValue IsNot Nothing And e.FormattedValue.ToString().Length > 0) Then
If IsNumeric(e.FormattedValue.ToString()) = False Then 'DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
e.Cancel = True
MsgBox("Error.Please input number.")
End If
End If
End Sub
C#.
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].IsNewRow) return;
decimal dci;
if (e.ColumnIndex == 4)
{
if (e.FormattedValue != null && e.FormattedValue.ToString().Length > 0)
{
if (!decimal.TryParse(e.FormattedValue.ToString(), out dci) || dci < 0)
{
e.Cancel = true;
MessageBox.Show("请输入数字或小数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
五,Datagridview 转为 datatable
''' <summary>
''' Convert a DataGridView to DataTable
''' </summary>
''' <param name="dgv"></param>
''' <returns></returns>
Public Function ToDataTable(ByVal dgv As DataGridView) As DataTable
Dim tb = New DataTable(dgv.Name)
'Add table column
For Each col In dgv.Columns.OfType(Of DataGridViewColumn)
tb.Columns.Add(col.Name)
Next
'Content
For Each dgvrow In dgv.Rows.OfType(Of DataGridViewRow)
Dim datarow = tb.NewRow()
For Each col In dgv.Columns.OfType(Of DataGridViewColumn)
datarow(col.Name) = Convert.ToString(dgvrow.Cells(col.Name).Value)
Next
tb.Rows.Add(datarow)
Next
Return tb
End Function
六,设置datagridview 的当前行
Dim curRow = datagridview1.Rows(5)
curRow.Selected = True
datagridview1.CurrentCell = curRow.Cells(0)