c#在TabControl内部动态创建的DataGridView中查找SelectedRow
本文关键字:DataGridView 查找 SelectedRow 创建 TabControl 内部 动态 | 更新日期: 2023-09-27 18:00:34
我有一个tabcontrol,datagridview是在tabcontrol的tabpage中动态创建的。我需要从活动数据网格视图中提取选定的行项目值。这个网格的名称也将被动态设置。我可以做些什么来从所选行中获取列值?以下是在表单加载事件中执行的代码
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);
}
将每个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();
}