2009-07-22 25 views
0

我想讓我當前的程序從動態創建的DataGridView中獲取信息。我設法將信息放入網格中,並執行所需的搜索,但是現在我真的陷入了困境。C#動態從DataGridView中取數據

我已經在datagridview中添加了一列,每列都包含一個按鈕。我想要做的是從列索引1中獲取數據的值,它與點擊按鈕位於同一行。混亂?無論如何,這裏是代碼:

 public void GetValues(...) 
    { 


     //Details regarding connection, querying and inserting table 
     . 
     . 
     . 

     DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn(); 
     buttonCol.Name = "ButtonColumn"; 
     buttonCol.HeaderText = "Select"; 
     buttonCol.Text = "Edit"; 
     //NB: the text won't show up on the button. Any help there either? 

     dataGridView1.Columns.Add(buttonCol); 
     dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick); 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      DataGridViewButtonCell button = (row.Cells["ButtonColumn"] as DataGridViewButtonCell); 

     } 
     dataGridView1.Columns["ButtonColumn"].DisplayIndex = 0; 


    } 


     void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
     { 
      //Here is where I'm having the trouble. What do I put in here??? 
     } 

感謝您的任何幫助,你可以給!

David。

回答

0

DataGridViewCellEventArgs包含非常有用的信息,如RowIndex。

因此,像(我不知道你想用價值做什麼):

String dataYouWant = dataGridView1.Rows[e.RowIndex].Cells[1].Value; 
+0

非常感謝,非常有幫助! – 2009-07-22 18:59:12

0

`

if (e.ColumnIndex != button_column_number) //column number of the button. 
        return; 
       dataGridView1.EndEdit(); 
       bool val; 
       if ((dataGridView1.Rows[e.RowIndex].Cells[1].Value) != null) // column index 1...as that's what you want. 
       { 
        //d stuff you want here. 
       } 
       else 
       { 
       } 

`

+0

非常深入 - 只是想知道「Bool val」變量有什麼用途? – 2009-07-22 19:01:10