我想将一些行从MS Excel复制并粘贴到我的C#Winforms应用程序中的richTextBox。用户将按下键盘上的CTRL + V并显示Excel网格线。如何确保粘贴的内容仅显示为文本?#
这似乎不起作用:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.V)
{
e.Handled = true;
string st = Clipboard.GetText();
richTextBox1.Text = st;
}
}
我无法使用文本框,因为我的代码如下所示:
private void button1_Click(object sender, EventArgs e)
{
richTextBox2.Clear();
richTextBox2.Focus();
string strValues;
strValues = richTextBox1.Text;
var textInEachLine = richTextBox1.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
string whereClause = string.Join("', '", textInEachLine).ToString();
richTextBox2.AppendText(" IN ( '" + whereClause + "')");
}
答案 0 :(得分:1)
更好的解决方案是将richTextBox转换为多行文本框。
答案 1 :(得分:0)
试用此代码
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
e.Handled = true;
string st = Clipboard.GetText();
richTextBox1.Text = st;
}
base.OnKeyDown(e);
}
private void richTextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.V) { e.IsInputKey = true; }
}
答案 2 :(得分:0)
我已经四处寻找更好的答案了。我提出了自己的解决方案,因为我无法摆脱我支持的应用程序中的RichTextBox。我编写了一个表单应用程序来查看原始RTF数据并从excel中粘贴了一些单元格。 空白的TextBox产生了......
{\ rtf1 \ ansi \ ansicpg1252 \ deff0 \ deflang1033 {\ fonttbl {\ f0 \ fnil Calibri;}} \ viewkind4 \ UC1 \ PARD \ F0 \ FS22 \看齐 }
当粘贴一些带有彩色文字的单元格时,它会显示出来......
{\ rtf1 \ ansi \ ansicpg1252 \ deff0 \ deflang1033 {\ fonttbl {\ f0 \ fnil Calibri;}} {\ colortbl; \ red255 \ green0 \ blue0; \ red0 \ green0 \ blue0;} \ viewkind4 \ uc1 \ trowd \ trgaph30 \ trleft-30 \ cellx1002 \ cellx2034 \ pard \ intbl \ cf1 \ f0 \ fs22 good text \ cell \ cf2 good text \ cell \ row \ intbl good text \ cell \ cf1 good text \ cell \ row \ PARD \ CF0 \看齐 }
我发现删除了' \ cell'或\ cellx ####'并将文本返回到另一个RichTextBox导致所有相关的格式被删除。似乎RichTextBox将删除无效格式。 有了这个,我在将文本粘贴到RichTextBox之前编写了以下方法。
private void CleanClipboardText()
{
string cleaned = Clipboard.GetText(TextDataFormat.Rtf);
if (cleaned != null & cleaned != String.Empty)
{
Regex regex = new Regex(@"\\cellx\d{4}?");
cleaned = regex.Replace(cleaned, " ");
regex = new Regex(@"\\cell");
cleaned = regex.Replace(cleaned, " ");
Clipboard.SetText(cleaned, TextDataFormat.Rtf);
}
}
这个" KeyDown"事件
private void RTB_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
RichTextBox rtb = sender as RichTextBox;
e.Handled = true;
CleanClipboardText();
rtb.Paste();
}
}
我使用了.Paste();
因为我不想覆盖整个框的文本richTextBox1.Text = st;
。但是,如果您愿意,您可能希望让CleanClipboardText方法返回一个rtf数据字符串,然后再设置RichTextBox.Rtf
。