How to Bind List<List<CustomObject>> to RadGridView (C# + Wpf) ?

1 Answer 44 Views
GridView
Thierry
Top achievements
Rank 1
Thierry asked on 09 Nov 2023, 07:43 PM

Hello,
please I need help to display the data of this type List<List<string>> in the component RadGridView.
Attached is a work in progress that I've started and I'm stuck.

Thanks for your help 

1 Answer, 1 is accepted

Sort by
0
Accepted
Dinko
Telerik team
answered on 10 Nov 2023, 11:36 AM

Hi Thierry,

To bind your models structure to the RadGridView, you can make a few adjustments in your code. You can set the ItemsSource of RadGridView to the Lines property in your CustomData class. Additionally, you could set AutoGenerateColumns to False since you are defining your own columns.

<telerik:RadGridView x:Name="gridView"
					 ItemsSource="{Binding Data.Lines}"
					 AutoGenerateColumns="False" />

In your view model there is an error which comes from the GetYourData method. The error is Cannot.Convert type List<List<string>> to GridView_BindCollection.CustomData. This occurs because the Data property in your MainViewModel class is of type CustomData, but you are trying to assign a List<List<string>> to it. To fix this, you could create an instance of CustomData in your GetYourData() method and populate its Lines property.

private CustomData GetYourData()
{
	CustomData customData = new CustomData();
	customData.Lines = new List<CustomDataLine>
	{
		new CustomDataLine { Line = new List<string> {"Colonne1", "Colonne2", "Colonne3"} },
		new CustomDataLine { Line = new List<string> {"Donnée1", "Donnée2", "Donnée3"} },
	};

	return customData;
}

In your scenario the DataContext will be null because you set it before population your view model Data property. In order to resolve this issue, you could reorder your MainWindow constructor like this:

public MainWindow()
{
	InitializeComponent();

	MainViewModel viewModel = new MainViewModel();
	viewModel.Data = GetYourData();

	this.DataContext = viewModel;
}

The result after these changes is as following:

In addition, I prepared a sample solution where this behavior is implemented.

Regards,
Dinko
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Thierry
Top achievements
Rank 1
commented on 10 Nov 2023, 07:15 PM

Thank you for your prompt reply and this technical solution.
Tags
GridView
Asked by
Thierry
Top achievements
Rank 1
Answers by
Dinko
Telerik team
Share this question
or