Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

c# - Getting System.Data.DataRowView while getting value from ComboBox

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...