簡體   English   中英

c#datagridview如何使用txtbox以其他形式傳遞值

[英]c# datagridview how to pass value using txtbox in other form

  • form1我有一個GUI按鈕可以選擇
  • form2是我的datagridview
  • 在form3中輸入姓名和mi
  • 我對form1的代碼是form2.show
  • 在我的form2上是form3.show
  • 我在form3中有一個代碼,該代碼使用計數器在datagridView1中輸入
  private void btnAdd_Click(object sender, EventArgs e) { int counter = 0; if (dataGridView1.Rows.Count > 1) { while (counter != dataGridView1.Rows.Count - 1) { if (dataGridView1.Rows[counter].Cells[0].Value.ToString() ==txtName.Text) { MessageBox.Show("name already exist"); return; } counter++; } } if (txtName.Text == "") { MessageBox.Show("name field should not be empty"); return; } else { dataGridView1.Rows.Add(txtName.Text); } 
  • 我的問題是,form3無法識別dataGridView1,我如何將form3中的文本框的值轉換為form2中的datagridview。

如果正在打開對話框,輸入了數據,然后關閉了對話框,則根本不應該調用Show 您應該改為調用ShowDialog ,該對話框將窗體顯示為模式對話框。 在這種情況下,調用者可以通過在顯示對話框之前設置屬性或傳遞方法參數來將數據傳遞到對話框中,然后通過獲取屬性或方法返回值來取回數據。 然后,由調用者決定使用數據做什么,這意味着您的form2可以填充自己的網格。

例如

using (var dialogue = new Form3())
{
    // Pass data in as required.
    dialogue.SomeProperty = someValue;

    // Display the dialogue...
    if (dialogue.ShowDialog() == DialogResult.OK)
    {
        // ...and get data out if the user clicks OK.
        someOtherValue = dialogue.SomeOtherProperty;

        // Use data here.
    }
}

您可以在對話表單中定義適當的成員以公開所需的數據。

Reference of DataGridViewReference of DataGridView傳遞給form 3

步驟1:創建form3的重載構造form3

DataGridView dg;

 public Form3(ref DataGridView dgv)
 {
    InitializeComponent();
    dg=dgv;
 }

步驟2:從Form2,如何調用,在form3 constructor傳遞form2 datagridview reference ...

form3 frm = new form3(ref datagridview1);
frm.show();

步驟3:您的Form3代碼。

     private void btnAdd_Click(object sender, EventArgs e)
     {
        int counter = 0;
        if (dg.Rows.Count > 1)
        {
             while (counter != dg.Rows.Count - 1)
             {
                 if (dg.Rows[counter].Cells[0].Value.ToString() ==txtName.Text)
                 {
                      MessageBox.Show("name already exist");
                      return;
                  }
                  counter++;
             }
        }
        if (txtName.Text == "")
        {
             MessageBox.Show("name field should not be empty");
             return;
        }
        else
        {
            dg.Rows.Add(txtName.Text);
        }
   }

暫無
暫無

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

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