2012-04-19 56 views
0

我从数据库加载到的dataGridView数据,有效果看起来像这样:获得PK值

Patients Data Grid View Sample

(在最终版本我宁愿隐藏PatientID列)

我想要做的是,当用户在相应行中的任何地方单击时(即用户单击“Doe”并且返回值为“2”),PatientID的返回值。任何人都可以给我一个提示如何做到这一点?我不认为有valueMember属性...我正在尝试Rowindex,但返回从顶部算起的行数值(D'uh ?!)

此外,有没有一种方法让用户突出整个点击单个单元格时行?

编辑:哦,上帝​​,我在深夜花了几个小时找到这一点,在早上,我放弃了,并张贴在这里...只是为了找到答案在5分钟后:仍然

string test = dataGridView1.Rows[e.RowIndex].Cells["PatientID"].FormattedValue.ToString(); 

,这留下了我关于突出显示整行的第二个问题。

回答

1

如果datagridview的绑定到一些数据源(DataView),则可以使用DataBoundItem属性,例如

DGV.CurrentRow.DataBoundItem["PatientID"] 

DGV.SelectedRows[0].DataBoundItem["PatientID"] 

DGVUnderlyingBindingSource.Current["PatientID"] 

如果DataGridView绑定到强类型数据源(例如BindingList),那么你可以用上面这样的:

((PatientType)DGV.CurrentRow.DataBoundItem).PatientID 

((PatientType)DGV.SelectedRows[0].DataBoundItem).PatientID 

((PatientType)PatientTypeBindingSource.Current).PatientID 

关于问题的第二部分,设置在DataGridView的SelectionMode属性为FullRowSelect

编辑

如果您隐藏该列,则无法使用编辑中的解决方案。为了通过使用.Cells[idx].FormattedValue来访问该值,该值必须是可见的。但即使隐藏了列,您也可以使用这个。

+0

dataGridView1.CurrentRow.DataBoundItem [“DEVICE_ID”]让我无法适用与[]索引到我假设你有型“对象” – cja 2013-03-06 11:09:33

+0

@cja的表达一个DataView作为数据源。在这种情况下,您应该像这样将'DataBoundItem'投射到'DataRowView':'((DataRowView)dataGridView1.CurrentRow.DataBoundItem)[“device_id”]'。您还需要自行转换返回的值。因为它被称为“device_id”,我想它是'int'所以这样做:'(int)((DataRowView)dataGridView1.CurrentRow.DataBoundItem)[“device_id”]' – 2013-04-01 10:05:39

0

对于第二个问题,将选择模式设置为FullRowSelect,并在用户点击完整行时突出显示。您可以设置在设计或代码这个属性:

DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;