簡體   English   中英

如何將datagridview的數據傳遞到其他表單的文本框?

[英]How can I pass data of datagridview to textboxes in other Form?

Datagridview位於Form2的Form1中的TextBoxes中。

使用Show()從Form1調用Form 2; dataGridView位於何處,然后將此信息傳遞到Form1中的文本框。

Form2中的代碼示例:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    Form1 exportar = new Form1();
    exportar.textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
    exportar.comboBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
    exportar.textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
    exportar.textBox3.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value.ToString();
    exportar.textBox4.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[4].Value.ToString();
    exportar.dateTimePicker1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[5].Value.ToString();
    exportar.dateTimePicker2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[6].Value.ToString();
    exportar.textBox7.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[7].Value.ToString();
    exportar.textBox8.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[8].Value.ToString();
    exportar.textBox9.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[9].Value.ToString();
    exportar.textBox10.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[11].Value.ToString();
}

這不起作用,但是當我放置exportar.Show()傳遞了信息。 問題是將Form1加倍。

您需要在Form2中引用Form1。 您可以在Form2的構造函數中傳遞它

private Form1 _form1;

public Form2 (Form1 form1)
{
    _form1 = form1;
}

您可以在Form1中創建並打開Form2,如下所示:

var form2 = new Form2(this);
form2.ShowDialog(this);

為了能夠訪問其他窗體的控件,必須在屬性窗口ModiferModifer更改為Internal

然后您可以設置以下值:

var row = dataGridView1.CurrentRow; // This is "the row".
                                    // No detour through the index is necessary.
_form1.textBox1.Text = row.Cells[0].Value.ToString();
_form1.comboBox1.Text = row.Cells[1].Value.ToString();

但是,如果使用數據綁定,事情會變得更簡單。 請參閱: 詳細的數據綁定教程

1.將其作為cunstrctor參數傳遞:

public Form2(string text){
      Textbox1. text = text;
}

Form2 f = new Form2("something to send to the form");
f.Show();

2.為Form2創建一個公共屬性:

public string TheText {get{return TextBox1.Text;}; set {textBox1.Text = value;};}

然后從第一種形式開始:

Form2 f = new Form2();
f.TheText = "Some text";
f.Show();

如果是強制性的,則將數據傳遞到其他形式的構造函數中。 或者以其他形式提供公共方法,該方法允許您分別設置數據。

例如

public void setTextBoxData(String text) { ,etc, etc }

然后,您可以在第二種形式上調用該方法,並從第一種形式傳遞所需的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM