2016-03-31 40 views
0

我正在尋找將datagridview值傳遞給另一個表單進行編輯。我可以找到很多代碼背後的例子,但我似乎無法找到一個將代碼從代碼背後取出的例子。將datagridview值傳遞給另一個表單

我的示例代碼

ProductView productView = new ProductView(); 

productview.txtbox1.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString(); 
productview.txtbox2.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString(); 
productview.txtbox3.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString(); 
productview.txtbox4.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString(); 
productview.ShowDialog(); 

這東西是允許把後面的代碼? 我嘗試儘可能少的代碼,只有必要的東西。

+1

你的意思是「儘量少放在後面的代碼」?你會在哪裏放置你的代碼? –

+0

我嘗試儘可能多地放在我的主持人/控制器/ ...但這種情況我不知道該怎麼做 – suspected

回答

0

取決於您如何定義「允許」。它適用於編譯器和.NET框架,但這是一個很好的做法嗎?那麼你需要以某種方式通過,但讓我們從beggining

  1. 不要對你的文本框,如「TextBox1中」等給他們一個名稱,其actaully意味着像「tbName」或「nameTextbox」或任何這是開始自我解釋。
  2. 如果ProductView Form專門用於顯示此細節,我將爲此類創建一個構造函數,它接受這些參數(最好是作爲一個類)。 因此,例如我會在下面的一些分離項目中創建一個新類。

public class ProductViewOptions 
{ 
    public string ProductName{ get; set; } 
    public decimal ProductPrice { get; set; } 
    ... 
} 

然後在ProductView窗體中創建上述類型的私有屬性並創建一個接受此類型參數的構造方法。它可能看起來像下面:

public class ProductView : Form 
{ 
    private ProductViewOptions productOptions; 
    public ProductView(ProductViewOptions ProductOptions) 
    { 
     this.productOptions = ProductOptions; 
    } 
    ... 
} 

由於這個代碼將更具可讀性和你的榜樣應該是這樣的:

ProductViewOptions productOptions = new ProductViewOptions(); 
productOptions.ProductName = this.dataGridView1.CurrentRow.Cells[1].Value.ToString(); 
productOptions.ProductPrice = this.dataGridView1.CurrentRow.Cells[2].Value.ToString(); 

ProductView productView = new ProductView(productOptions); 
productView.ShowDialog(); 

新的代碼塊是自explantatory易讀並保持。

相關問題