如何将我的行值从datagridView传递到另一个表单?

时间:2013-11-10 12:23:50

标签: c# winforms datagridview buttonclick

我有两个表单 - Main和AddToCurrentInventory。在Main表单中我有一个datagridview和一个按钮'Add to Current Inventory'.I我想从datagridview中选择一行(通过单击)并传递几个值当我点击“添加到当前库存”按钮时打开AddtoCurrentInventory表单控件的列。因此,我必须同时触发两个事件。我试图这样做,但它们没有被触发。当我点击按钮,它会打开另一个表单,但值不会从所选行传递。我哪里出错了?

以下是我定义的两种方法的代码 -

private void dataGridInventoryItems_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int rowIndex = e.RowIndex;
        DataGridViewRow row = dataGridViewInventoryItems.Rows[rowIndex];
        AddToCurrentInventory form=new AddToCurrentInventory();
        form.labelItemno.Text=row.Cells[1].Value.ToString();
        //label on the form AddtocurrentInventory
        form.textBox_itemname.Text = row.Cells[2].Value.ToString();
       //textbox on the form AddToCurrentInventory
        form.cmbUnit.Text= row.Cells[3].Value.ToString();
       //ComboBox on the form AddToCurrentInventory

    }

    private void button_addtocurrent_Click(object sender, EventArgs e)
    {
        AddToCurrentInventory formAddToCurrentInventory = new AddToCurrentInventory();

        formAddToCurrentInventory.Show();
    }

这些方法是以主要形式制作的。

3 个答案:

答案 0 :(得分:0)

您的代码无法正常工作,因为在单击“单击”中,您正在创建AddToCurrentInventory的实例并设置字段值,但在按钮单击内,您将创建另一个AddToCurrentInventory实例以显示该表单。使用设置值的同一实例来显示表单。

答案 1 :(得分:0)

您必须使用一些变量来存储CellClick中提取的所有值,然后使用这些变量将信息传递到表单。但是,您应该声明一个包含新表单的变量。您的表单也应该只创建一次。以下是应该如何做的:

//You just need handle the button Click event    
private void button_addtocurrent_Click(object sender, EventArgs e)
{                  
    DataGridViewRow row = dataGridViewInventoryItems.CurrentRow;   
    if(!row.IsNewRow) {
      AddToCurrentInventory form=new AddToCurrentInventory();        
      form.labelItemno.Text=row.Cells[1].Value.ToString();
      //label on the form AddtocurrentInventory
      form.textBox_itemname.Text = row.Cells[2].Value.ToString();
      //textbox on the form AddToCurrentInventory
      form.cmbUnit.Text= row.Cells[3].Value.ToString();
      form.Show();
    }
}

答案 2 :(得分:0)

声明一个全局变量用于存储行的当前索引。说

Public int row =0;


 private void button_addtocurrent_Click(object sender, EventArgs e)
{                  
 row = new_tab_Object.CurrentCell.RowIndex; 

  if (row != -1)
    {
  AddToCurrentInventory form=new AddToCurrentInventory();

  form.labelItemno.Text=row.Cells[1].Value.ToString();

  //label on the form AddtocurrentInventory

  form.textBox_itemname.Text = row.Cells[2].Value.ToString();
  //textbox on the form AddToCurrentInventory
  form.cmbUnit.Text= row.Cells[3].Value.ToString();
  form.Show();
}

}