Getting System.Data.DataRowView when getting value from ComboBox

I am trying to get data from a database according to the item selected in ComboBox , but when I try to access the selected ComboBox item, it gives me "System.Data.DataRowView" [...?]

I did the same with a simple select request in another function, and this works fine, but I don't know why it does not work in this request:

 _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 someone tell me what could be the problem?

+6
source share
3 answers

SelectedItem is a data object bound to a ComboBox data source, which in this case is equal to a DataRowView .

You need to drop the SelectedItem in the DataRowView , and then extract the corresponding value from it.

You can do it 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() 

from:

 sValue 

This will gracefully handle the case when the 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 set this field name in the combobox DisplayMember or ValueMember , then you can simply use this property instead to save yourself some pain in 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 .

+14
source

When you bind to an ADO DataTable , you really bind to an ADO DataView (which is a collection of DataRowViews). This means that SelectedItem will always be a DataRowView .

To get a related DataRow, you can call

 DataRow row = ((DataRowView)SelectedItem).Row 
+1
source

This is for DropDownList. Many developers want to get the Data Member value from the drop-down list below a function that will help to easily get the value ... if there is any comment on the proposal below!

  public string RadDropDownSelectValue(RadDropDownList radDropDownList) { string str = ""; foreach (RadListDataItem item in radDropDownList.SelectedItems) { DataRowView dv = (DataRowView)item.Value; str = dv.Row[0].ToString(); } return str; } 
0
source

Source: https://habr.com/ru/post/903029/


All Articles