Hi, I am in full agreement with Andy and Thomas. They both explained the concept elegantly.
I show only those steps that do the same with a dataset only.
MVVM (ModelView ViewModel) I am not discussing here.
Xaml looks like this:
<Grid Name="myGrid" ShowGridLines="False"> <Label Height="28" Margin="12,5,0,0" Name="lblName" VerticalAlignment="Top" HorizontalAlignment="Left" Width="55">Name</Label> <TextBox Height="23" Margin="73,8,85,0" Name="txtName" VerticalAlignment="Top" /> <Label Height="28" Margin="12,39,0,0" Name="lblPlace" VerticalAlignment="Top" HorizontalAlignment="Left" Width="55">Place</Label> <TextBox Height="23" Margin="73,44,85,0" Name="txtPlace" VerticalAlignment="Top" /> <Button Height="23" HorizontalAlignment="Left" Margin="20,82,0,0" Name="btnAddRecord" VerticalAlignment="Top" Width="75" Click="btnAddRecord_Click">Add Record</Button> <ListView Margin="31,119,27,45" Name="listView" *ItemsSource="{Binding}"*> <ListView.View> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Place" DisplayMemberBinding="{Binding Place}"/> </GridView> </ListView.View> </ListView> </Grid>
Create a dataset in a .CS file
private DataSet MyDataSet() { DataTable dtInformation1 = new DataTable(); dtInformation1.Columns.Add("Name"); dtInformation1.Columns.Add("Place"); dtInformation1.Rows.Add(txtName.Text, txtPlace.Text); DataTable dtInformation2 = new DataTable(); dtInformation2.Columns.Add("Name"); dtInformation2.Columns.Add("Place"); dtInformation2.Rows.Add(txtName.Text + "2", txtPlace.Text + "2"); DataSet Ds = new DataSet(); Ds.Tables.Add(dtInformation1); Ds.Tables.Add(dtInformation2); return Ds; }
Next, in the click Button event, write the following
private void btnAddRecord_Click (object sender, RoutedEventArgs e)
{ **listView.ItemsSource = MyDataSet().Tables[0].DefaultView; - OR - listView.ItemsSource = MyDataSet().Tables[1].DefaultView;** }
NB ~ You cannot assign a ListView source to a dataset.
Why? You can ask? A data set, in simple words, is a set of data tables.
Suppose you have 5 different data types. And say that none of their column names, nor the column numbers match.
Now you have assigned all this data to your data set. How does the source of control know which source it should bind?
To overcome this situation, either create a custom data type that will have all the columns of these discrete data and assign values ββto this custom one, and then bind it to the source.
Or you need to explicitly specify the data type in the data source
But I always prefer to use the MVVM pattern for this kind of operation.