none
WPF DataGrid : Add/Edit/Delete Item by Row RRS feed

  • Question

  •  
    Hi,

    I really appreciate the new DATAGRID control in WPF which I was wondering for days.

    Can anyone answer me with VB code for the below queries:
    I have 4 textboxes and a datagrid with 4 columns.
    1. How to add text from textboxes to datagrid??
    2. How to show text in textboxes from selected row in datagrid??
    3. How to replace the selected row's text in datagrid with text from textboxes??
    4. How to delete the selected row in datagrid??

    I appreciate if you can attach as sample.

    Thanks in advance.
    Friday, November 14, 2008 3:43 AM

Answers

  • Hi,

     

    Here is an example of adding, deleting, updating information in DataGrid.

     

    In this example, we create an ObservableCollection class as data source, which implements INotifyPropertyChanged,  set  a collection of class Customers as its children. Next, we bind the data source to the DataGrid.

     

    -->1. How to add text from textboxes to datagrid??

    First, you get the text from the TextBoxes, then instantiate a new Customer class, add it into the ObservableCollection instance class. As a result, then DataGird in UI will show the added item.

     

    -->2. How to show text in textboxes from selected row in datagrid??

     

    You can set these TextBox bind to the DataGrid,  make sure that the path is SelectedItem, so when you selecte a item from the DataGrid, the text of TextBox will change correspondingly.

     

    -->3. How to replace the selected row's text in datagrid with text from textboxes??

     

     First, get the text from the TextBox,  then create a new customer. Next, remove the selected Customer instance from the  collection. Lastly, add a new Customer to the collection.


    4. How to delete the selected row in datagrid??

     

    Just remove the selected Customer instance from the collection.

     

    XAML code:

    <Window x:Class="WpfDataGrid.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="300" Width="300"

        xmlns:my="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

        xmlns:local="clr-namespace:WpfDataGrid"

            >

            <StackPanel>

                    <my:DataGrid AutoGenerateColumns="True" Name="datagrid"  />

            <GroupBox Header="AddData">

                <!--add data-->

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition />

                        <RowDefinition />

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition/>

                        <ColumnDefinition />

                        <ColumnDefinition />

                    </Grid.ColumnDefinitions>

                    <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />

                     <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />

                     <TextBlock Text="ID" Grid.Row="0" Grid.Column="2" />

                     <TextBox Name="txtID" Grid.Row="1" Grid.Column="0" />

                     <TextBox Name="txtName" Grid.Row="1" Grid.Column="1" />

                     <TextBox Name="txtSecNumber" Grid.Row="1" Grid.Column="2" />

                </Grid>

            </GroupBox>

            <!--show the selected item-->

                <GroupBox Header="Show Selected info">

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition />

                        <RowDefinition />

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition/>

                        <ColumnDefinition />

                        <ColumnDefinition />

                    </Grid.ColumnDefinitions>

                    <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />

                     <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />

                     <TextBlock Text="SecNumber" Grid.Row="0" Grid.Column="2" />

                     <TextBox Name="txtShowID"  Grid.Row="1" Grid.Column="0" Text="{Binding ElementName=datagrid,Path=SelectedItem.ID}" />

                     <TextBox  Name="txtShowName" Grid.Row="1" Grid.Column="1" Text="{Binding ElementName=datagrid,Path=SelectedItem.Name}" />

                     <TextBox  Name="txtShowSecNumber" Grid.Row="1" Grid.Column="2" Text="{Binding ElementName=datagrid,Path=SelectedItem.SecNumber}" />

                </Grid>

                    </GroupBox>

            <StackPanel Orientation="Horizontal" >

                <Button  Content="Add"  Click="btnAdd" Width="50" Height="30" />

                <Button  Content="Update"  Click="btnUpdate" Width="50" Height="30" />

                <Button  Content="Delete"  Click="btnDelete" Width="50" Height="30" />

            </StackPanel>

     

        </StackPanel>

    </Window>

     

    In the code behind:


    namespace
    WpfDataGrid

    {

      

        public partial class Window1 : Window

        {

            ObservableCollection<Customer> col;

            public Window1()

            {

                InitializeComponent();

                col = new ObservableCollection<Customer>();

                col.Add(new Customer() { ID = 1, Name = "Name1", SecNumber = "mynumber1" });

                col.Add(new Customer() { ID = 2, Name = "Name2", SecNumber = "mynumber2" });

                col.Add(new Customer() { ID = 3, Name = "Name3", SecNumber = "mynumber3" });

                col.Add(new Customer() { ID = 4, Name = "Name4", SecNumber = "mynumber4" });

                datagrid.ItemsSource = col;

     

               

            }

            private void btnAdd(object sender, RoutedEventArgs e)

            {

                int id=0;

                try

                {

                     id = int.Parse(txtID.Text.Trim());

                     col.Add(new Customer() { ID = id, Name = txtName.Text.Trim(), SecNumber = txtSecNumber.Text.Trim() });

                }

                catch

                {

                    MessageBox.Show("ID must be int type");

     

                }

     

            }

            private void btnDelete(object sender, RoutedEventArgs e)

            {

                if (datagrid.SelectedIndex >= 0)

                {

                    //remove the selectedItem from the collection source

                    Customer customer = datagrid.SelectedItem as Customer;

                    col.Remove(customer);

                }

     

            }

     

            private void btnUpdate(object sender, RoutedEventArgs e)

            {

                if (datagrid.SelectedIndex >= 0)

                {

                    // get the selected's infomation first

                    Customer newCustomer = new Customer();

                    newCustomer.ID = int.Parse(txtShowID.Text);

                    newCustomer.Name = txtShowName.Text.Trim();

                    newCustomer.SecNumber = txtShowSecNumber.Text.Trim();

     

                    // remove the old information

                    Customer customer = datagrid.SelectedItem as Customer;

                    col.Remove(customer);

     

                    //add a new customer

                    col.Add(newCustomer);

                }

                else { MessageBox.Show("select"); }

     

            }

        }

        public class Customer

        {

            public int ID { get; set; }

            public string Name { get; set; }

            public string SecNumber { get; set; }

        }

    }


    If you have any questions with this, please feel free to ask.

     

    Thanks.

     

     

     


    Jim Zhou -MSFT
    Thursday, November 20, 2008 4:44 AM

All replies

  • Hi,

     

    Here is an example of adding, deleting, updating information in DataGrid.

     

    In this example, we create an ObservableCollection class as data source, which implements INotifyPropertyChanged,  set  a collection of class Customers as its children. Next, we bind the data source to the DataGrid.

     

    -->1. How to add text from textboxes to datagrid??

    First, you get the text from the TextBoxes, then instantiate a new Customer class, add it into the ObservableCollection instance class. As a result, then DataGird in UI will show the added item.

     

    -->2. How to show text in textboxes from selected row in datagrid??

     

    You can set these TextBox bind to the DataGrid,  make sure that the path is SelectedItem, so when you selecte a item from the DataGrid, the text of TextBox will change correspondingly.

     

    -->3. How to replace the selected row's text in datagrid with text from textboxes??

     

     First, get the text from the TextBox,  then create a new customer. Next, remove the selected Customer instance from the  collection. Lastly, add a new Customer to the collection.


    4. How to delete the selected row in datagrid??

     

    Just remove the selected Customer instance from the collection.

     

    XAML code:

    <Window x:Class="WpfDataGrid.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="300" Width="300"

        xmlns:my="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

        xmlns:local="clr-namespace:WpfDataGrid"

            >

            <StackPanel>

                    <my:DataGrid AutoGenerateColumns="True" Name="datagrid"  />

            <GroupBox Header="AddData">

                <!--add data-->

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition />

                        <RowDefinition />

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition/>

                        <ColumnDefinition />

                        <ColumnDefinition />

                    </Grid.ColumnDefinitions>

                    <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />

                     <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />

                     <TextBlock Text="ID" Grid.Row="0" Grid.Column="2" />

                     <TextBox Name="txtID" Grid.Row="1" Grid.Column="0" />

                     <TextBox Name="txtName" Grid.Row="1" Grid.Column="1" />

                     <TextBox Name="txtSecNumber" Grid.Row="1" Grid.Column="2" />

                </Grid>

            </GroupBox>

            <!--show the selected item-->

                <GroupBox Header="Show Selected info">

                <Grid>

                    <Grid.RowDefinitions>

                        <RowDefinition />

                        <RowDefinition />

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition/>

                        <ColumnDefinition />

                        <ColumnDefinition />

                    </Grid.ColumnDefinitions>

                    <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />

                     <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />

                     <TextBlock Text="SecNumber" Grid.Row="0" Grid.Column="2" />

                     <TextBox Name="txtShowID"  Grid.Row="1" Grid.Column="0" Text="{Binding ElementName=datagrid,Path=SelectedItem.ID}" />

                     <TextBox  Name="txtShowName" Grid.Row="1" Grid.Column="1" Text="{Binding ElementName=datagrid,Path=SelectedItem.Name}" />

                     <TextBox  Name="txtShowSecNumber" Grid.Row="1" Grid.Column="2" Text="{Binding ElementName=datagrid,Path=SelectedItem.SecNumber}" />

                </Grid>

                    </GroupBox>

            <StackPanel Orientation="Horizontal" >

                <Button  Content="Add"  Click="btnAdd" Width="50" Height="30" />

                <Button  Content="Update"  Click="btnUpdate" Width="50" Height="30" />

                <Button  Content="Delete"  Click="btnDelete" Width="50" Height="30" />

            </StackPanel>

     

        </StackPanel>

    </Window>

     

    In the code behind:


    namespace
    WpfDataGrid

    {

      

        public partial class Window1 : Window

        {

            ObservableCollection<Customer> col;

            public Window1()

            {

                InitializeComponent();

                col = new ObservableCollection<Customer>();

                col.Add(new Customer() { ID = 1, Name = "Name1", SecNumber = "mynumber1" });

                col.Add(new Customer() { ID = 2, Name = "Name2", SecNumber = "mynumber2" });

                col.Add(new Customer() { ID = 3, Name = "Name3", SecNumber = "mynumber3" });

                col.Add(new Customer() { ID = 4, Name = "Name4", SecNumber = "mynumber4" });

                datagrid.ItemsSource = col;

     

               

            }

            private void btnAdd(object sender, RoutedEventArgs e)

            {

                int id=0;

                try

                {

                     id = int.Parse(txtID.Text.Trim());

                     col.Add(new Customer() { ID = id, Name = txtName.Text.Trim(), SecNumber = txtSecNumber.Text.Trim() });

                }

                catch

                {

                    MessageBox.Show("ID must be int type");

     

                }

     

            }

            private void btnDelete(object sender, RoutedEventArgs e)

            {

                if (datagrid.SelectedIndex >= 0)

                {

                    //remove the selectedItem from the collection source

                    Customer customer = datagrid.SelectedItem as Customer;

                    col.Remove(customer);

                }

     

            }

     

            private void btnUpdate(object sender, RoutedEventArgs e)

            {

                if (datagrid.SelectedIndex >= 0)

                {

                    // get the selected's infomation first

                    Customer newCustomer = new Customer();

                    newCustomer.ID = int.Parse(txtShowID.Text);

                    newCustomer.Name = txtShowName.Text.Trim();

                    newCustomer.SecNumber = txtShowSecNumber.Text.Trim();

     

                    // remove the old information

                    Customer customer = datagrid.SelectedItem as Customer;

                    col.Remove(customer);

     

                    //add a new customer

                    col.Add(newCustomer);

                }

                else { MessageBox.Show("select"); }

     

            }

        }

        public class Customer

        {

            public int ID { get; set; }

            public string Name { get; set; }

            public string SecNumber { get; set; }

        }

    }


    If you have any questions with this, please feel free to ask.

     

    Thanks.

     

     

     


    Jim Zhou -MSFT
    Thursday, November 20, 2008 4:44 AM
  • Hi Jim,

    Thanks for your reply. I really appreciate your effort in sending me the code.

    I will try it.

    Meantime, can I know how to set collection other than CLASS?? For example: LIST, STRUCTURE or anyother simple way for collections?? I have many & different datagrids in several TABITEMS. Creating class for all datagrids will be troublesome. Can I know simple way of creating collection for each datagrid??

    Thanks in advance.
    Friday, November 21, 2008 1:35 AM
  • Hi Jim Zhou

    Thanks for such an informative example but I am also having same problem concerning update e.g like editing data from Textboxes and when you press btnupdate then update datagrid and database, but my main concern is: How do you change this code to work on Entity Framework?

    1) this is my xaml code for my UI

    <Grid>

            <Grid.RowDefinitions>

                <RowDefinition Height="55"/>

                <RowDefinition Height="200"/>

                <RowDefinition Height="*"/>

                <RowDefinition Height="35"/>

            </Grid.RowDefinitions>

            <Label Grid.Row="0" FontFamily="Segoe" FontWeight="Bold" FontSize="22" Foreground="#555" Margin="10,2,0,2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Product Lists" />

            <DataGrid x:Name="ProductList" Grid.Row="1" Margin="10,10,10,10" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionChanged="ProductList_SelectionChanged"/>

            <GroupBox Grid.Row="2" Header="Edit Product" VerticalAlignment="Stretch" Name="groupBoxBind">

                <Grid>

                    <Label Content="Product Name" Height="Auto" HorizontalAlignment="Left" Margin="10,1,0,0" Name="ProductName" VerticalAlignment="Top" Width="Auto" Foreground="Black" FontWeight="Bold"/>

                    <TextBox   TextWrapping="Wrap" Margin="115,5,0,0" VerticalAlignment="Top" TabIndex="1" Text="{Binding Path=ProductName,UpdateSourceTrigger=PropertyChanged}" x:Name="txtName" Height="Auto" Width="145" HorizontalAlignment="Left" DataContext="{Binding}" />

                    <TextBox TextWrapping="Wrap" Height="auto" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding Path=ProductCode,UpdateSourceTrigger=PropertyChanged}" x:Name="txtProductCode" Margin="115,30,0,0"  Width="145"/>

                    <Label Content="Product Code" Height="Auto" HorizontalAlignment="Left" Margin="10,26,0,0" Name="Code" VerticalAlignment="Top" Width="Auto" Foreground="Black" FontWeight="Bold"/>

                    <TextBox x:Name="txtDescription" Height="Auto" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="115,56,0,0" Text="{Binding Path=Description,UpdateSourceTrigger=PropertyChanged}" Width="145"/>

                    <Label Content="Description" Height="Auto" HorizontalAlignment="Left" Margin="11,51,0,0" VerticalAlignment="Top" Width="auto" Foreground="Black" FontWeight="Bold"/>

                    <Label Content="Product Type" Height="Auto" HorizontalAlignment="Left" Margin="9,77,0,0" VerticalAlignment="Top" Width="auto" Foreground="Black" FontWeight="Bold" Name="label3"/>

                    <TextBox x:Name="txtType" Height="Auto" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="115,82,0,0" Text="{Binding Path=ProductType, UpdateSourceTrigger=PropertyChanged}" Width="145"/>

                    <TextBox x:Name="txtPrice" Height="Auto" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="115,106,0,0" Text="{Binding Path=ProductPrice, StringFormat={}{0:C}, UpdateSourceTrigger=PropertyChanged}" Width="145"/>

                    <Label Content="Product Price" Height="Auto" HorizontalAlignment="Left" Margin="6,108,0,0" VerticalAlignment="Top" Width="auto" Foreground="Black" FontWeight="Bold" Name="label5"/>

                </Grid>

            </GroupBox>   

            <Button Grid.Row="3" HorizontalAlignment="Right" Margin="0,0,120,10" x:Name="btnEdit" Click="btnEdit_Click" VerticalAlignment="Bottom" Width="100" Content="Edit Product" />

            <Button Grid.Row="3" HorizontalAlignment="Right" Margin="0,0,10,10" x:Name="NewProduct" Click="NewProduct_Click"  VerticalAlignment="Bottom" Width="100" Content="New Product" />

            <TextBlock Grid.Row="3"  TextWrapping="Wrap" Margin="6,12,0,0" VerticalAlignment="Top"  Text="{Binding Path=CreateDate,Mode=TwoWay}" x:Name="txtDate" Height="Auto" Width="Auto" FontWeight="Bold" Foreground="Black" HorizontalAlignment="Left"/>

            <Button Content="Close" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="317,4,0,0"  VerticalAlignment="Top" Width="75" x:Name="btnClose" Click="btnClose_Click"/>

               </Grid>

    2) My Entity Framework Model Contains Product Table

     

    with the following columns ProductID int PK,

    ProductName nvarchar(50),

    ProductCode nvarchar(50), 

    ProductType nvarchar(50), 

    Description nvarchar(50), 

    CreateDate DateTime 

    and ProductPrice money  

     

     

    3) In my example I have separated my Project with layers like on Business Object contain Public Product Class :INotifyPropertyChanged ,

    my DataAccess Layer have Entity FrameWork ProductModel. working fine

    My UI is WPF Userinterface xaml

    Ok on my MainWindow.cs I tried to write btnUpdate to update my datagrid(ProductList) and update to database this is my code for Update

    private void btnEdit_Click(object sender, RoutedEventArgs e)

    {

    if (ProductList.SelectedIndex >= 0)

    {

    //get selected information first

    Product newProduct = new Product();

    newProduct.ProductName = txtName.Text.Trim();

    newProduct.ProductPrice = (decimal)(12.00);//decimal.Parse(txtPrice.Text);

    newProduct.ProductType = txtType.Text.Trim();

    newProduct.ProductCode = txtProductCode.Text.Trim();

    newProduct.Description = txtDescription.Text.Trim();

    newProduct.CreateDate = (DateTime)(DateTime.Now);//DateTime.Now;//

    Product product = ProductList.SelectedValue as Product;

    col.Remove(product);

    //col.Add(newProduct);

    db.SaveChanges();

    MessageBox.Show("Row is updated successfully");

    }

    else

    {

    MessageBox.Show("Select");

    }

    }

    first I get exception complaining about converting string to decimal and  converting string to DateTime. And when I press btnEdit it does not Update to Database... My last layer is  WCF Service not included in the solution because I am still struggling with WCF

    with kind regard

    Brianbk from South Africa

    email kagisobk@gmail.com

     

    Thursday, February 24, 2011 12:19 PM
  • hi Excellent
    Wednesday, October 8, 2014 6:18 PM