我有一个简单的dataGridView填充了东西,现在我希望能够右键单击左侧突出显示整行,这样我就可以插入或删除整行。我已经搜索了一段时间,但大部分时间都是针对单个单元格,我正在寻找在整行上使用的上下文菜单。
还有一个类似的问题,但最终并不完全是我试图做的事情。
提前谢谢!!
答案 0 :(得分:0)
我找到了一种非常简单的方法来做我想做的事情。它是这样的:
首先,挂钩mouseDown事件:
dataGridView1.MouseDown += new MouseEventHandler(this.dataGridView1_MouseClick);
然后,创建与mouseDown事件共同响应的例程..
private void dataGridView1_MouseClick(Object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu cm = new ContextMenu();
this.ContextMenu = cm;
cm.MenuItems.Add(new MenuItem("&Cut", new System.EventHandler(this.cut_Click)));
cm.MenuItems.Add(new MenuItem("&Copy", new System.EventHandler(this.copy2_Click)));
cm.MenuItems.Add(new MenuItem("&Paste", new System.EventHandler(this.paste2_Click)));
cm.Show(this, new Point(e.X, e.Y));
}
}
然后添加您的事件例程,例如:
private void cut_Click(Object sender, EventArgs e)
{
if (this.dataGridView1.GetCellCount(DataGridViewElementStates.Selected) > 0)
{
try
{
Clipboard.SetDataObject(this.dataGridView1.GetClipboardContent());
}
catch (System.Runtime.InteropServices.ExternalException)
{
MessageBox.Show("Clipboard could not be accessed. Please try again.");
}
}
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
}
}
将复制的单元格添加到剪贴板。然后粘贴它们,例如:
private void paste2_Click(Object sender, EventArgs e)
{
char[] rowSplitter = { '\r', '\n' };
char[] columnSplitter = { '\t' };
// Get the text from clipboard
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);
// Split it into lines
string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
// Get the row and column of selected cell in grid
int r = dataGridView1.SelectedCells[0].RowIndex;
int c = dataGridView1.SelectedCells[0].ColumnIndex;
// Add rows into grid to fit clipboard lines
if (dataGridView1.Rows.Count < (r + rowsInClipboard.Length))
{
dataGridView1.Rows.Add(r + rowsInClipboard.Length - dataGridView1.Rows.Count);
}
// Loop through the lines, split them into cells and place the values in the corresponding cell.
for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++)
{
// Split row into cell values
string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);
// Cycle through cell values
for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
{
// Assign cell value, only if it within columns of the grid
if (dataGridView1.ColumnCount - 1 >= c + iCol)
{
DataGridViewCell cell = dataGridView1.Rows[r + iRow].Cells[c + iCol];
if (!cell.ReadOnly)
{
cell.Value = valuesInRow[iCol+1];
}
}
}
}
}
我使用[col + 1]因为列表中的第一项始终是空白(“”)。希望这有助于某人。这个对我有用! :d