2015-11-05 156 views
1

我只想將數據從另一個表單傳遞給DataGridView?如何從其他表單傳遞數據到DataGridView?

我有2點窗口的形式:

  • form1包含DataGridView1button_frm1DataGridView有3列,已經有一些數據(6行),DataGridView1 modifiers = Public。

  • form2包含textBox1button_frm2。現在

,當我點擊button_frm1窗口2出現,接下來當我點擊button_frm2在文本框中的值應該選擇行插入DataGridView1在column0。但是,相反,我得到這個錯誤:

Index was out of range. Must be non-negative and less than the size of the collection.

請幫助我如何從Form2的文本框中的值插入DataGridView1在Form1。遵循什麼步驟? 非常感謝您提前。

這裏是我嘗試的代碼:

Form1中:

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


    } 
} 
+0

如何填充您的DataGridView? – StepUp

+0

@naouf你試過我的方法嗎?我理解正確嗎? – StepUp

+0

嗨StepUp。謝謝您的回覆。我仍然沒有嘗試它,因爲我是c#的新手,你的代碼對我來說是新的東西,所以我仍然試圖理解它。但是,一旦我嘗試它,我會讓你知道。你能告訴我在c#的哪個區域應該搜索來理解你的代碼嗎?謝謝。 – naouf

回答

0

起初創建包含關於事件的數據的類:

public class ValueEventArgs : EventArgs 
{ 
    private string _smth; 
    public ValueEventArgs(string smth) 
    { 
     this._smth = smth; 
    } 
    public string Someth_property 
    { 
     get { return _smth; } 
    }  
} 

然後聲明一個事件和事件處理程序的窗體2:

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窗體2:

public delegate void FieldUpdateHandler(object sender, ValueEventArgs e); 
public event FieldUpdateHandler FieldUpdate; 

,並在事件的事件處理程序的窗體2的按鈕的「點擊」:

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); 
} 
相關問題