在从ComboBox获取值时获取System.Data.DataRowView [英] Getting System.Data.DataRowView while getting value from ComboBox
问题描述
我试图根据 ComboBox
中选择的项目从数据库中获取数据,但是当我尝试访问所选的 ComboBox
item它给我System.Data.DataRowView[...?]
我在另一个函数中使用简单的select查询并且工作正常,但我不知道为什么它不工作在这个查询:
_dataAdapter.SelectCommand.CommandText = SELECT lt.Name FROM Leader as lt LEFT JOIN Material as mt ON lt.Student_id = mt.lead_id其中lt.Name =+'+ cmbLeader.SelectedItem.ToString()+';任何人都可以告诉我可能是什么问题?
$ b =h2_lin>解决方案 SelectedItem
是绑定到 ComboBox
的数据源,在这种情况下 DataRowView
。
您需要强制转换 SelectedItem
到 DataRowView
,然后从中检索相应的值。
请执行以下操作:
DataRowView oDataRowView = cmbLeader.SelectedItem as DataRowView;
string sValue =;
if(oDataRowView!= null){
sValue = oDataRowView.Row [YourFieldName] as string;
}
然后替换(在CommandText中):
cmbLeader.SelectedItem.ToString()
与:
sValue
这将正常处理DataRowView为null的情况。
YourFieldName
上面的代码应该是数据源中包含Name值的字段的名称。如果您在组合框的 DisplayMember
或 ValueMember
属性中设置了此字段名称,那么您只需使用此属性当此字段发生更改或您想在其他位置重复使用此代码时,请保存自己一些心痛:
sValue = oDataRowView .Row [cmbLeader.DisplayMember]作为字符串;或者,您可以使用 cmbLeader.SelectedValue
或 。
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
is the data object that is bound to the ComboBox
's data source, which in this case is DataRowView
.
You need to cast SelectedItem
to DataRowView
, then retrieve the appropriate value from it.
You can do this as follows:
DataRowView oDataRowView = cmbLeader.SelectedItem as DataRowView;
string sValue = "";
if (oDataRowView != null) {
sValue = oDataRowView.Row["YourFieldName"] as string;
}
then replace (in your CommandText):
cmbLeader.SelectedItem.ToString()
with:
sValue
This will gracefully handle the case where DataRowView is null.
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;
Alternatively, you can use cmbLeader.SelectedValue
.
这篇关于在从ComboBox获取值时获取System.Data.DataRowView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!