WPF ListBox - how to put values from dataTable? - wpf

I have ListBox and want to put values in this listbox from a DataTable:
listBoxVisibleFields.DataContext = SelectedFields;
Where SelectedFields is a DataTable filled with data. But this code does not work. My ListBox is empty. As I remember, in WinForms was sucha a thing for list box like ValueMember and DisplayMember, but in WPF I dont find something like that...
Does someone know how to fill simply my ListBox from DataTable?

The property you are looking for is ItemsSource instead of DataContext. The property most closely resembling ValueMember is called SelectedValuePath (see this example). The analogon for DisplayMember is called DisplayMemberPath.
EDIT: So, your code should look like this:
DataTable SelectedFields = ...;
listBoxVisibleFields.SelectedValuePath = "myID";
listBoxVisibleFields.DisplayMemberPath = "myTextField";
listBoxVisibleFields.ItemsSource = SelectedFields.DefaultView;
Alternatively, the two path values can be set in XAML
<ListBox ... SelectedValuePath="myID" DisplayMemberPath="myTextField" />
which is a bit more elegant.

Here is my code, hope is usefull
Dim connectionString As String = "Data Source=(local);Database=Catalogos;UID=sa;Password=S1santan"
Dim conSQL As New SqlClient.SqlConnection()
conSQL.ConnectionString = connectionString
conSQL.Open()
Debug.Print("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'")
Dim adaptSQL As New SqlClient.SqlDataAdapter("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'", conSQL)
Dim DatosCP As New DataSet
adaptSQL.Fill(DatosCP, "CodigoPostal")
'Here you select the table inside a data set
ListBox1.ItemsSource = DatosCP.Tables("CodigoPostal").DefaultView
'Here select which field to show
ListBox1.DisplayMemberPath = "d_asenta"
'and at last here you select the field you want to use to select values from
ListBox1.SelectedValuePath = "ID"
conSQL.Close()

Related

Why will my Datagridview not display information from the DataTable to which I bound it?

I have created a form with a datagridview on it. I bound that DGV to a datatable which is constructed from a table in a SqlServer CE database. I was able to add, edit and delete records and save changes to the database.
Then, I set AutoGenerateColumns to False so I could set up the DGV with nice formatting. To begin, I added only one column:
'/// Set Up DataGridView
With dgvMaterials
.AutoGenerateColumns = False
'.Columns.Add("MaterialName", "Material")
End With
Dim col As DataGridViewColumn
'
col = New DataGridViewColumn
With col
.Name = "Material"
.DataPropertyName = "MaterialName"
.Width = 200
'.HeaderText = "Material"
End With
dgvMaterials.Columns.Add(col)
dgvMaterials.DataSource = stuff.Materials
(Stuff is an instance of a class where I do my SQL stuff, Materials is the name of the DataTable)
Now I must have checked DataPropertyName a hundred times and I verified that there are records in the DataTable, but they will not show in the DGV. Why?
As always thanks in advance for any help offered.
Folks, the answer is simple: I put my column in as type DataGridViewColumn and for whatever reason it had to be DataGridViewTextBoxColumn to work. I switched it out, now the datagridview works like a champ.

VB.Net binding filtered dataview to Listbox

I am attempting to perform a filter on an Access database with Visual Studio 2010. The user will enter the search criteria into a textbox and I would like the results to be displayed in a listbox with the ability to update other fields depending on the selecteditem from the listbox. The current code I have is:
Dim dv As New DataView
With dv
.Table = subcategoryDataSet.Tables("Subcategory")
.AllowDelete = False
.AllowEdit = False
.AllowNew = False
.RowFilter = "Description LIKE '" & txtSearchBox.Text & "*'"
.Sort = "ID"
End With
'Now I am lost
Not sure if I need to create a datasource from the dv table? Or how to bind it properly to the listbox, or if I even need to bind it to the listbox?
Any help would be greatly appreciated.Thanks!
You should simply set the DataSource of the Listbox to your DataView and set the DisplayMember to the field that you want to see in the Listbox.
Something like this
ListBox1.DataSource = dv
ListBox1.DisplayMember = "Description"

Text entered in WPF DatagridTextboxColumn and value selected in DatagridComboboxColumn are not displayed when focus is lost

My question might seem repeatetive as there are similar questions in StackOverflow like,
https://stackoverflow.com/questions/5733782/how-to-retain-value-in-datagridcomboboxcolumn-of-wpfs-datagrid
https://stackoverflow.com/questions/6101441/creating-wpf-datagrid-dynamically-with-dynamically-created-drop-down-box-using-d
but I cudn't find an answer pertaining to my requirements.
I generate a WPF datagrid dynamically which takes columns from a metadata file(excel) based on certain conditions. The datagrid needs to be generic and hence I cannot bind the Datagrid itself during creation. I bind the DatagridCombobobox columns dynamically and was able to get the values in them too.
Now my problem is, once I select a value in the DatagridCombobobox or enter text in the DatagridTextboxColumn and then move to another cell/ row, this text and selection disappears.
How do I enable the Datagrid cell/row to remember my entered text or selection dynamically?
I checked the answer of a similar question in DataGridComboBoxColumn cell not displaying selected item text? but it is for a static datagrid. Since my datagrid creation is dynamic, I donot know how to use this solution. Kindly help.
I am stuck up in this and its taking a lot of my time :(
Regards,
Niranjan.
Dynamic DataGrid creation:
Dim setupGrid = "<my:DataGrid AutoGenerateColumns='False' Name='grdSetup' " & "xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'" & " xmlns:sdk = 'http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk'" & " xmlns:x = 'http://schemas.microsoft.com/winfx/2006/xaml'" & " xmlns:TAB = 'http://fabtab.codeplex.com'" & " xmlns:my='http://schemas.microsoft.com/wpf/2008/toolkit' " & " >"
setupGrid = setupGrid & "<my:DataGrid.Columns>"
...
...
...
setupGrid = setupGrid & "</my:DataGrid.Columns>"
setupGrid = setupGrid & "</my:DataGrid>"
Dim sr = New MemoryStream(Encoding.ASCII.GetBytes(setupGrid))
Dim pc = New ParserContext()
pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation")
pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml")
Dim grdElement As UIElement = DirectCast(System.Windows.Markup.XamlReader.Load(sr, pc), UIElement)
Dim grdSetup As DataGrid = DirectCast(grdElement, DataGrid)
My DataGridCombobox code is similar :
setupGrid = setupGrid & "<my:DataGridComboBoxColumn x:Name='" & dr.Item("ParameterName").ToString.Trim & "' Header='" & dr.Item("ParameterName") & "' SelectedValuePath='" & dr.Item("ValueColumn") & "' DisplayMemberPath='" & dr.Item("DisplayColumn") & "' />"
This string value will be added to the above DataGrid string and converted to UIElement as shown in the above DataGrid code. I add my Datagrid to an ItemsControl dynamically :
Me.DynamicContent.Items.Add(grdElement)
where DynamicContent is ItemsControl.
In the UserControl_Loaded event, I find each ComboBox in my Datagrid thru :
Dim dynamicGrid as DataGrid = DynamicContent.ItemContainerGenerator.ContainerFromIndex(0)
Dim comboColumns = dynamicGrid.Columns.OfType(Of DataGridComboBoxColumn)()
For index As Integer = 0 To comboColumns.Count - 1
comboColumns(index).ItemsSource = DirectCast(dt, IListSource).GetList()
Next
where dt is a Datatable which consists of data to be to my ComboBox. It has the SelectedValuePath and DisplayMember path of the combobox as the columns.
I cannot set the SelectedItemBinding and the SelectedValueBinding for the DatagridComboboxColumn before hand as it is dynamic and varies for different ComboColumns. I dont know how these can be set in the above loaded event.
Pls let me know what I am doing wrong? Or what can be done so that I can be able to retain the values even after the focus is lost.
Sorry for the lengthy description :(

How do I bind a SQL bit field to a True/False combobox or listbox?

I store True/False values as bit fields in SQL Server. The fields are nullable. What is the XAML syntax to bind a bit field to a WPF combo box so the user can choose True/False or blank (null)?
By the way, I'm binding to a strongly-typed dataset/datatable. Drag and drop binding has simplified binding to other datatypes. I certainly don't mind editing the XAML, but I'm wondering if drag and drop can be made to work in this scenario?
Just as a suggestion for anyone else who comes across this issue (without having to do the XAML stuff), I did the following using Linq (VB 2008):
Private Sub BindMyCombo()
Dim yesNo As String() = {"No", "Yes"} 'Or false, true or nay, yay -whatever
Dim bits = From bit In yesNo _
Select New With { _
.BitVal = Cbool(Array.IndexOf(yesNo, bit)), _
.BitText = bit _
}
With Me.myBitComboBox
'Clear anything in the combo first if necessary...
.DataSource = Nothing
.Items.Clear()
'New binding in case there are more "bits" to be used elsewhere in your form
.BindingContext = New BindingContext
.DataSource = bits.ToList
.DisplayMember = "BitText"
.ValueMember = "BitVal"
End With
End Sub
After that it's just a matter of doing the binding with the dataset. When you do, specify that when the bit value is null to set the combos selectedValue to blank or nothing, for example...
With Me.myBitComboBox
.DataBindings.Clear()
.DataBindings.Add(New Binding("SelectedValue", myDataSetName, "myBitFieldName", _
True, DataSourceUpdateMode.OnPropertyChanged, Nothing))
.SelectedValue = IIf(mdDataSetName.myBitFieldName.ToString = "", "", _
myDataSetName.myBitFieldName)
End With
I hope this helps anyone else that comes across this issue (like me).
You will likely need to create a value converter (a class which implements the IValueConverter interface) which can translate the value of a bit field to a boolean value. Part of the problem, out of the box, is that how do you represent a null value as a boolean state? That typically depends on the business process or rules.

How do I assign selected WPF datagrid row columns to variables. (VB.NET)

I have a datagrid with customer data such as ID, name, email, phone etc.
When I select a row (with a button or selectionchanged) I want to store that row's columns in variables like
dim email as string
dim name as string
email = dgCustomers.theselectedrow.theselectedcell
name = dgCustomers.theselectedrow.theselectedcell
If I have a datatable with only one row I know I can get column data with:
dim email as string = CustomerDataTableInstance.rows(0).Item("Email")
I don't know how to get the selected row number though when I have several rows and the user clicks one/uses the keyboard.
The datagrid is bound to a datatable, not a class with object collections.
Any help is appreciated!
Did you try the SelectedItem or SelectedIndex properties?
I don't know much about using datatables, but I suspect you can get some kind of row object that represents a row from the datatable, by using SelectedItem, which you can then use to get each of the columns you want--which is just like binding to a collection of objects works.
If that doesn't work, try the SelectedIndex property. I'm pretty sure it exists, but I might be wrong since I never use it--I always just bind my data to SelectedItem.
I just answered a similar question for someone else. Please see VB.NET WPF How to get the column value from datagrid? for more detail, but Benny Jobigan is correct, you would use the SelectedIndex to get at your row, then use the Item collection to get at your column values. It would look something similar to this:
Dim View As DataView = TryCast(DataGrid1.ItemsSource, DataView)
If View IsNot Nothing Then
Dim ViewRow As DataRowView = View.Item(DataGrid1.SelectedIndex)
Dim ColumnValue As Object = ViewRow.Item("ID") ' or ViewRow.Item(0) for positional value.
' do something with ColumnValue here.
End If
Hope that helps!

Resources