2015-07-01 58 views
1

我有一個tabcontrol和datagridview是在tabcontrol的tabpage中動態創建的。我需要從活動的datagridview中提取選定的行項目值。該網格的名稱也將被動態設置。我能做些什麼來獲得選定行的列值?下面是它在窗體加載事件c#在動態創建的DataGridView中查找SelectedRow TabControl內部

foreach (DataTable dtTable in Ds.Tables) 
     { 
DataGridView dgv = new DataGridView(); 
      //dgv.DataSource = dtTable; 
      dgv.AllowUserToAddRows = false; 
      dgv.AllowUserToDeleteRows = false; 
      dgv.ColumnHeadersHeightSizeMode =  System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; 
      dgv.Dock = System.Windows.Forms.DockStyle.Fill; 
      dgv.Location = new System.Drawing.Point(3, 3); 
      dgv.Name = "dgv_" + dtTable.TableName; 
      dgv.ReadOnly = true; 
      dgv.Size = new System.Drawing.Size(725, 322); 
      dgv.TabIndex = 0; 
      dgv.AutoGenerateColumns = false; 

      foreach (DataColumn dtCol in dtTable.Columns) 
      { 
       DataGridViewColumn column = new DataGridViewTextBoxColumn(); 
       column.FillWeight = 1; 
       column.Name = dtCol.ColumnName; 
       column.DataPropertyName = dtCol.ColumnName; 
       dgv.Columns.Add(column); 
      } 


      //dgv.Columns.AddRange(columns); 
      dgv.DataSource = null; 
      dgv.DataSource = dtTable; 



      lblInfo.Text = string.Format("Rows : {0} ; Columns : {1}", dtTable.Rows.Count, dtTable.Columns.Count); 

      TabPage tpInstdata = new System.Windows.Forms.TabPage(); 
      tpInstdata.Controls.Add(dgv); 
      tpInstdata.Location = new System.Drawing.Point(4, 22); 
      tpInstdata.Name = "tp_" + dtTable.TableName; 
      tpInstdata.Padding = new System.Windows.Forms.Padding(3); 
      tpInstdata.Size = new System.Drawing.Size(725, 322); 
      tpInstdata.TabIndex = 1; 
      tpInstdata.Text = dtTable.TableName; 
      tpInstdata.UseVisualStyleBackColor = true; 
      tcInstTab.TabPages.Add(tpInstdata); 
} 
+0

添加代碼是最有幫助的 –

回答

0

每個DGV在你的foreach循環相同的SelectionChanged事件處理程序連接執行的代碼:

dgv.SelectionChanged += aDataGridView_SelectionChanged; 

的事件處理函數看起來是這樣的:

private void aDataGridView_SelectionChanged(object sender, System.EventArgs e) 
    { 
     string aValue = ((DataGridView)sender).SelectedRows[0].Cells["ColumnOfYourInterest"].Value.ToString(); 
    }