如何将数据网格视图选定的行值以另一种形式传递给文本框?



我在.NET 4.5.2上使用Windows Forms。我有 2 种表格。Form1 有一个包含数据库中的字段的 DataGridView 和一个在单击时显示 Form2 的按钮。Form2 有一个文本框。我想在单击 Form1 中的按钮时,用 Form1 数据网格视图字段之一中的文本填充它。可能吗?Form2 文本框修饰符设置为公共,但它仍然不起作用。

我试过:

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.Show事件,在新创建的窗体(我们称之为 Form2(中将所需的值从 DataGridView 传递到 TextBox。您可以尝试在button1_Click事件处理程序中用这段代码替换代码(或者可能只是使用 Form2 类在文件中创建 Display事件处理程序(:

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);  

附言为什么要使用Convert.ToString()而不是像我在示例中那样简单地在 Value 属性上调用ToString()方法?

首先,您应该公开 Form1 的 datagridview 修饰符。 当您单击 Form1 中的按钮时,打开 Form2 并将此代码写入 Form2_Load((。

Form1 frm = (Form1)Application.OpenForms["Form1"];
int row = frm.DataGridView1.CurrentRow.Index;
Textbox1.Text = Convert.ToString(frm.DataGridView1[0, row].Value);
Textbox2.Text = Convert.ToString(frm.DataGridView1[1, row].Value);

这应该有效。

Form2 fr = new Form2();
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
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)
{
fr.ShowDialog();  
}

相关内容

最新更新