使用datagridview的上下文菜单 [英] contextmenustrip with datagridview
问题描述
我再次在表单中使用了datagrid ...
我添加了网格contexmenustrip ...
菜单项新建..."和编辑..."
例如...我的网格中有十行...而我的网格高度= 20行高度
所以我的表格50full/50empty
当我将鼠标移至空白区域和列标题时,我想禁用"edit ..."项并启用"new ..."项.
当我将鼠标移到整个区域时,要禁用新建..."项并启用编辑..."项.
我使用此代码进行选择:
I have datagrid in my form again...
I added to grid contexmenustrip...
menustrip items "New..." and "Edit..."
For example... ten rows in my grid... and my grid height=20 rows height
so my gridtable 50full/50empty
when i move to mouse empty area and columnheaders, i want to disable "edit..." item and enable "new..." item.
when i move to mouse full area , want to disable "new..." item and enable "edit..." item.
i use this code for my selection:
Private Sub dg_one_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dg_one.CellMouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
For Each row As DataGridViewRow In dg_one.SelectedRows
row.Selected = False
Next
End If
dg_one.Rows(e.RowIndex).Selected = True
lblid.Text = dg_one.Item(0, e.RowIndex).Value
End Sub
我尝试了columnheaders.visible = false和dg_one.height = rowcount * 20 ...虽然有些奏效,但我不喜欢可见性...
我该怎么办?
I tried columnheaders.visible=false and dg_one.height=rowcount * 20... it some works but i dont like visiblity...
What can i do for?
推荐答案
恕我直言,您正在过度设计该功能,即使选择了一行,您为什么也要禁用新选项.这将迫使您的用户将鼠标移至空白区域或标题区域,以便能够添加记录,而不仅仅是单击鼠标右键,非常直观.
我可以理解编辑被禁用了,但是我会基于它是否存在选定的行来进行.
IMHO you are over engineering the functionality, why would you want to disable the new option, even if a row is selected. This would force your user to move the mouse to a blank or header area to be able to add a record instead of simply right clicking, very counter intuitive.
I can understand the edit being disabled but I would base it on wether there is a selected row.
您说50full/50empty表示所有都是从数据库中获取的,因为50条记录中有数据,其中50个没有数据.
因此您只能使用编辑选项"来编辑网格中的行.数据库中已经存在Bec空记录.
如果要启用或禁用ContextMenustrip中的任何MenuItem.
处理CellMouseDown事件
you said 50full/50empty that means All Are Fetched From DB, in that 50 Records are having Data, 50 are not Having Data.
so you can have Edit Option only to Edit the Rows in Your Grid. Bec Already Empty Record Exists in DB.
If you want to Enable or Disable Any MenuItem in ContextMenustrip.
Handle CellMouseDown Event
For Exa:
private void dgrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if(e.RowIndex >=0)
{
dgrid.ClearSelection();
dgrid[e.ColumnIndex,e.RowIndex].Selected=True;
dgrid.ContextMenuStrip=Contextmenustrip1;
if (!string.IsNullOrEmpty(dgrid.Rows[e.RowIndex].Cells["SomeFieldName"].Value.ToString()))
{
newToolstripMenuItem.Enable=True;
editToolstripMenuItem.Enabled=False;
}
else
{
newToolstripMenuItem.Enable=False;
editToolstripMenuItem.Enabled=True;
}
}
else
{
dgrid.ContextMenuStrip=null;
}
这篇关于使用datagridview的上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!