>我有一个要求,我需要在数据网格视图中为多个页面执行查找和替换 - 它工作正常。问题是,在我找到一个特定的单词并替换它之后,如果我再次单击"查找和替换"按钮,则较早的查找和替换值将消失。
怎么做呢?
代码提供如下:
public string toFind = "";
public string toReplace = "";
private void btnFindandReplace_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.cmbColumnCombo.DataSource = cmbList;
f.ShowDialog();
toFind = f.txtfind.Text;
toReplace = f.txtreplace.Text;
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[f.cmbColumnCombo.Text].Value.ToString().ToLower().Contains(f.txtfind.Text.ToLower()))
{
if (!string.IsNullOrEmpty(f.txtfind.Text))
{
dataGridView1.Rows[i].Cells[f.cmbColumnCombo.Text].Value =
dataGridView1.Rows[i].Cells[f.cmbColumnCombo.Text].Value.ToString().Replace(f.txtfind.Text, f.txtreplace.Text);
}
}
}
}
尝试在
btnFindandReplace_Click 方法中初始化 toFind 和 toReplace 变量。
在按钮单击事件处理程序之外声明 Form 对象。这将使您的表单全局化并在同一对象上运行。