[英]c# datagridview how to pass value using txtbox in other form
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); }
如果正在打開對話框,輸入了數據,然后關閉了對話框,則根本不應該調用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 DataGridView
的Reference 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.