我有DataGridView
三列,所有三列都是DataGridViewTextBoxColumn
,现在我想通过鼠标选择单元格文本。我尝试了以下方法:
dgView.ReadOnly = false;
private void dgView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is TextBox)
{
(e.Control as TextBox).ReadOnly = true;
}
}
但这个伎俩不起作用。
答案 0 :(得分:2)
如果你的 的dataGridView
AllowUserToAddRows, AllowUserToEditRows
选择为false的属性,然后只能使用像这样的代码从单元格中复制该值:
public void Form1()
{
//here is code of constructor
.....
contextMenuStrip1 = new ContextMenuStrip();
System.Windows.Forms.ToolStripMenuItem copyStripMenuItem;
copyStripMenuItem = new ToolStripMenuItem();
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
copyStripMenuItem });
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(169, 98);
copyStripMenuItem.Name = "copyToolStripMenuItem1";
copyStripMenuItem.Size = new System.Drawing.Size(168, 22);
copyStripMenuItem.Text = "Copy";
copyStripMenuItem.Click += new EventHandler(copyStripMenuItem_Click);
dataGridView1.ContextMenuStrip = contextMenuStrip1;
....
}
void copyStripMenuItem_Click(object sender, EventArgs e)
{
CellCopy();
}
public void CellCopy()
{
DataGridViewCell cell = dataGridView1.CurrentCell;
if (cell != null)
{
DataGridViewColumn col = dataGridView1.Columns[cell.ColumnIndex];
if (col is DataGridViewTextBoxColumn)
{
if (cell.IsInEditMode)
{
TextBox txt = dataGridView1.EditingControl as TextBox;
if (txt != null)
txt.Copy();
}
else
{
string val = cell.FormattedValue == null ? "" : cell.FormattedValue.ToString();
if (val == "")
Clipboard.Clear();
else
Clipboard.SetText(val);
}
}
}
}
<强>更新强>
此外,如果您需要通过鼠标单击来复制dataGridView1值,您可以这样写。
public void Form1_Load(object sender, EventArgs e)
{
there is some code of constructor here
.....
dataGridView1.CellContentDoubleClick+=new DataGridViewCellEventHandler(dataGridView1_CellContentDoubleClick);
......
}
void dataGridView3_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
CellCopy();
}
/// <summary>
/// Copy the current value in the buffer
/// </summary>
public void CellCopy()
{
DataGridViewCell cell = dataGridView1.CurrentCell;
if (cell != null)
{
DataGridViewColumn col = dataGridView1.Columns[cell.ColumnIndex];
if (col is DGW_NewCellsColumn)
{
if (cell.IsInEditMode)
{
TextBox txt = dataGridView1.EditingControl as TextBox;
if (txt != null)
txt.Copy();
}
else
{
string val = cell.FormattedValue == null ? "" : cell.FormattedValue.ToString();
if (val == "")
Clipboard.Clear();
else
Clipboard.SetText(val);
}
}
}
}