我在.NET 4.5.2上使用Windows窗体。我有2种表格。Form1具有一个DataGridView,其中包含来自数据库的字段,以及一个单击时显示Form2的按钮。Form2具有一个TextBox。当我单击Form1中的按钮时,我想用Form1 DataGridView字段之一的文本填充它。可能吗?Form2文本框修改器设置为public,但仍无法使用。
我试过了:
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
Form2 fr = new Form2();
int row = DataGridView1.CurrentRow.Index;
fr.Textbox1.Text = Convert.ToString(DataGridView1[0, row].Value);
fr.Textbox2.Text = Convert.ToString(DataGridView1[1, row].Value);
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fr = new Form2();
fr.ShowDialog();
}
存在问题是因为您使用ShowDialog()
而不是方法Show()
。从有关堆栈溢出的答案:
Show函数以非模式形式显示表单。这意味着您可以单击父表单。
ShowDialog以模态形式显示表单,这意味着您无法转到父表单。
以某种方式与将值从一种形式传递到另一种形式发生交互,我认为这是因为第一种形式在ShowDialog()
方法之后被阻塞(暂停),因此阻止了您从DataGridView复制值。
如果您ShowDialog()
故意使用方法,则可以尝试以某种方式绕过此限制。例如,我设法通过使用Owner属性(也请选中此答案)和Form.Shown事件,将所需的值从DataGridView传递到新创建的Form中的TextBox(也称为Form2)中。您可以尝试在button1_Click事件处理程序中用这段代码替换代码(或者可能只是使用Form2类在文件中创建Shown事件处理程序):
Form2 fr = new Form2();
int row = DataGridView1.CurrentRow.Index;
fr.Shown += (senderfr, efr) =>
{
// I did null check because I used the same form as Form2 :)
// You can probably omit this check.
if (fr.Owner == null) return;
var ownerForm = (Form1)fr.Owner;
fr.Textbox1.Text = ownerForm.DataGridView1[0, row].Value.ToString();
fr.Textbox2.Text = ownerForm.DataGridView1[1, row].Value.ToString();
};
fr.ShowDialog(this);
PS为什么您会像在示例中那样使用Convert.ToString()
而不是简单地ToString()
在Value属性上调用方法?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句