C# 只读DataGridViewColumn中的Selectabletext
我有一个C# 只读DataGridViewColumn中的Selectabletext,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个DataGridView,其中包含的列必须是ReadOnly。 问题是,该值不可选择。。。我需要使它能够复制和粘贴鼠标只 此外,DataGridView.SelectionMode必须是DataGridViewSelectionMode.FullRowSelect或DataGridViewSelectionMode.RowHeaderSelect 有没有办法解决这个问题 我搜索了一些属性,比如Editable之类的,但是我只找到了ReadOnly属性 编辑: 我只需要ReadOnly单元
DataGridView
,其中包含的列必须是ReadOnly
。
问题是,该值不可选择。。。我需要使它能够复制和粘贴鼠标只
此外,DataGridView.SelectionMode
必须是DataGridViewSelectionMode.FullRowSelect
或DataGridViewSelectionMode.RowHeaderSelect
有没有办法解决这个问题
我搜索了一些属性,比如Editable之类的,但是我只找到了ReadOnly
属性
编辑:
我只需要ReadOnly单元格中的单元格值。在这段代码中,我以编程方式创建了列,并将第一列设置为ReadOnly。通过选择模式
CellSelect
,您可以最容易地复制只读数据。如果使用FullRowSelect
则始终复制整行(除非进入编辑模式并复制可编辑单元格)
仅使用鼠标从只读单元格获取数据的一种简单方法(根据我的经验,是用户友好的)是创建CellMouseClick
事件处理程序
示例
private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if ( e.Button == MouseButtons.Right )
{
//Set text to clipboard
Clipboard.SetText( dataGridView[e.ColumnIndex, e.RowIndex].Value.ToString() );
}
}
要使用DataGridViewSelectionMode.FullRowSelect获取单击的单元格,请执行以下操作:
DataGridViewCell clickedCell;
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Right)
{
dataGridView1.ClearSelection();
clickedCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
clickedCell.Selected = true;
var cellRectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
// Show context menu with 'Copy' option
contextMenuStrip1.Show(dataGridView1, cellRectangle.Left + e.X, cellRectangle.Top + e.Y);
}
}
catch (Exception ex)
{
throw ex;
}
}
然后将contextMenuStrip
添加到表单中,并在copy
项中单击事件(上下文菜单将从上述事件中显示):
只读与不可编辑相同。如果执行FullRowSelect,则意味着您将始终复制并粘贴整行。你想要什么?我只需要只读单元格中的单元格值。我想,用户可以用鼠标选择整个值或只是它的一个子串。你应该在问题中用鼠标指定。。。我刚刚添加了一个使用ctrl+C组合键的示例。我将立即为鼠标编辑它。这是一个使用鼠标复制它的简单方法示例,文本选择(子字符串)将无法通过这种方式进行,因为这是datagridview中的编辑模式。
DataGridViewCell clickedCell;
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Right)
{
dataGridView1.ClearSelection();
clickedCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
clickedCell.Selected = true;
var cellRectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
// Show context menu with 'Copy' option
contextMenuStrip1.Show(dataGridView1, cellRectangle.Left + e.X, cellRectangle.Top + e.Y);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.SetText(clickedCell.Value.ToString());
}