[英]How can I pass data to DataGridView from another form?
我只想將數據從另一種形式傳遞到DataGridView?
我有2個Windows表單:
form1
包含DataGridView1
和button_frm1
。 DataGridView
有3列,已經有一些數據(6行),並且DataGridView1
修飾符= Public。
form2
包含textBox1
和button_frm2
。
現在,當我單擊button_frm1
出現form2;接下來,當我單擊button_frm2
時, button_frm2
的值插入到選定行中column0的DataGridView1
中。 但是,我得到了這個錯誤:
索引超出范圍。 必須為非負數並且小於集合的大小。
請幫助我如何將form2中的textBox值插入到form1中的DataGridView1中。 遵循什么步驟? 提前非常感謝您。
這是我嘗試的代碼:
表格1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button_frm1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
}
表格2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button_frm2(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
textBox1.Text= frm1.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}
}
首先,創建一個包含有關事件數據的類:
public class ValueEventArgs : EventArgs
{
private string _smth;
public ValueEventArgs(string smth)
{
this._smth = smth;
}
public string Someth_property
{
get { return _smth; }
}
}
然后在Form2上聲明一個事件和事件處理程序:
public delegate void FieldUpdateHandler(object sender, ValueEventArgs e);
public event FieldUpdateHandler FieldUpdate;
在Form2的按鈕的事件“ Click”的事件處理程序中:
private void button_frm2(object sender, EventArgs e)
{
//Transfer data from Form2 to Form1
string dataToTransfer=textBox1.Text;
ValueEventArgs args = new ValueEventArgs(str);
FieldUpdate(this, args);
this.Close();
}
然后寫出您從form1調用form2的位置:
private void button_frm1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.FieldUpdate += new AddStuff.FieldUpdateHandler(af_FieldUpdate);
frm2.Show();
}
void af_FieldUpdate(object sender, ValueEventArgs e)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = e.Someth_property;
row.Cells[1].Value = "YourValue";
/*or
this.dataGridView1.Rows.Add("1", "2", "three");
this.dataGridView1.Rows.Insert(0, "one", "two", "three");
*/
dataGridView1.Rows.Add(row);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.