在从 ComboBox 获取值的同时获取 System.Data.DataRowView [英] Getting System.Data.DataRowView while getting value from ComboBox
问题描述
我正在尝试根据 ComboBox
中选择的项目从数据库中获取数据,但是当我尝试访问所选的 ComboBox
项目时,它给了我System.Data.DataRowView" [...?]
I'm trying to get data from database according to the item selected in the ComboBox
but when I try to access the selected ComboBox
item it gives me "System.Data.DataRowView" [...?]
我在另一个函数中用一个简单的选择查询做了同样的事情,效果很好,但我不知道为什么它在这个查询中不起作用:
I did the same thing with a simple select query in another function and that works fine but I don't know why it doesn't work in this query:
_dataAdapter.SelectCommand.CommandText = "SELECT lt.Name FROM Leader as lt LEFT JOIN Material as mt ON lt.Student_id=mt.lead_id where lt.Name=" + "'" + cmbLeader.SelectedItem.ToString() + "'";
谁能告诉我可能是什么问题?
Can anybody tell me what might be the problem?
推荐答案
SelectedItem
是绑定到 ComboBox
的数据源的数据对象,在这个案例是DataRowView
.
SelectedItem
is the data object that is bound to the ComboBox
's data source, which in this case is DataRowView
.
您需要将 SelectedItem
转换为 DataRowView
,然后从中检索适当的值.
You need to cast SelectedItem
to DataRowView
, then retrieve the appropriate value from it.
您可以这样做:
DataRowView oDataRowView = cmbLeader.SelectedItem as DataRowView;
string sValue = "";
if (oDataRowView != null) {
sValue = oDataRowView.Row["YourFieldName"] as string;
}
然后替换(在您的 CommandText 中):
then replace (in your CommandText):
cmbLeader.SelectedItem.ToString()
与:
sValue
这将优雅地处理 DataRowView 为空的情况.
This will gracefully handle the case where DataRowView is null.
YourFieldName
应该是数据源中包含Name值的字段的名称.如果您在组合框的 DisplayMember
或 ValueMember
属性中设置了此字段名称,那么您可以只使用此属性,以便在此字段时为自己节省一些心痛更改或当您想在其他地方重用此代码时:
YourFieldName
in the above code should be the name of the field in the data source that contains the Name value. If you have set this field name in the combobox's DisplayMember
or ValueMember
properties, then you can just use this property instead in order to save yourself some heartache down the road when this field changes or when you want to reuse this code elsewhere:
sValue = oDataRowView.Row[cmbLeader.DisplayMember] as string;
或者,您可以使用 cmbLeader.SelectedValue
.
这篇关于在从 ComboBox 获取值的同时获取 System.Data.DataRowView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!