user2889489
user2889489

Reputation: 687

DataGrid in WPF using VisualStudio C#

I have 3 TexBoxes,Buttons and DataGrid in my window. when I enter the data into the TextBox and click on the button it should add into the DataGrid .I need a code for how to add, delete and get data. I'm new to wpf please help me with the code. This is my Xaml code

  <Window x:Class="simpledatagrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="IDDATA" Height="350" Width="525">
<Grid  >
    <DataGrid BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" Name="dgsample" Margin="200,10,10,75"></DataGrid>

    <Label  Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/>
    <Label  Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/>
    <Label  Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/>

    <TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>

    <Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" />
    <Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" />
    <Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" />
</Grid>

This is my .cs code

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
         List<User> users = new List<User>();
                    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                    dgsample.ItemsSource = users;
            }

    private void Get_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Add_Click(object sender, RoutedEventArgs e)
    {

    }

    private void Delete_Click(object sender, RoutedEventArgs e)
    {

    }
    }  
}

Upvotes: 1

Views: 597

Answers (4)

Ram Nivas
Ram Nivas

Reputation: 142

first , you can use ObservableCollection instead of List. because ObservableCollection has INotifyCollectionChanged defaultly. ObservableCollection is TwoWayBinding.

ObservableCollection<User> users = new  ObservableCollection<User>();
public MainWindow()
{
    InitializeComponent();

                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

                dgsample.ItemsSource = users;
}

private void Get_Click(object sender, RoutedEventArgs e)
{
     if (this.tb1.Text != string.Empty) { User currentUser = users.Single(select => select.Id == Int32.Parse(this.tb1.Text)); this.tb2.Text = currentUser.Name; this.tb3.Text = currentUser.Salary; } 
}

private void Add_Click(object sender, RoutedEventArgs e)
{
      users.Add(new User() { Id = 105, Name = "gin5", Salary = 100 });
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
   users.RemoveAt(0);
}

Upvotes: 1

Tafari
Tafari

Reputation: 3059

Define User class:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }

    public User()
    {

    }

    public User(int id, string name, int salary)
    {
        Id = id;
        Name = name;
        Salary = salary;
    }
}

Then in your MainWindow.xaml.cs file change your List to ObservableCollection (you will need to add;

using System.Collections.ObjectModel; // EDIT

and then:

ObservableCollection<User> users;

public MainWindow()
{
    users = new ObservableCollection<User>();
    users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
    users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
    users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });

    InitializeComponent();
    dgsample.ItemsSource = users;
}


private void Add_Click(object sender, RoutedEventArgs e)
{
    users.Add(new User(){Id = Int.Parse(tb1.Text), Name = tb2.Text, Salary = Int.Parse(tb3.Text)});
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
    users.RemoveAt(dgSample.SelectedIndex);
}

// you can get what you need just selected proper User proprety
private void Get_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(( (User)dgSample.Items[dgSample.SelectedIndex]).Name);
}

Upvotes: 0

Omri Btian
Omri Btian

Reputation: 6547

If you are new to WPF you should start by doing things the WPF way. In WPF you should manipulate your data which is binded to the UI, instead of manipulating the UI directly. This design pattern is known as MVVM.

In your case, you will have a class (known as the ViewModel) which will contain the collection of your User items (known as the Model).

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
         Users = new ObservableCollection<User>();
                users.Add(new User() { Id = 101, Name = "gin", Salary = 10 });
                users.Add(new User() { Id = 102, Name = "alen", Salary = 20 });
                users.Add(new User() { Id = 103, Name = "scott", Salary = 30 });
    }

    public ObservableCollection<User> Users { get; set; }
}

In your MainWindow (known as the View) code-behind all you should do is set it's DataContext as the MainWindowViewModel.

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainWindowViewModel();
}

In the window itself, bind the collection to the Users propery in your ViewModel

 <DataGrid BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" Name="dgsample" Margin="200,10,10,75" ItemsSource="{Binding Users}"></DataGrid>

As for your TextBoxes, as they are intended to crate a new User, you can have another User property on your ViewModel

public User NewUser { get; set; }

And bind them to their matching properties in your User class

<TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Id}"/>
<TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Name}"/>
<TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100" Text="{Binding Path=NewUser.Salary}"/>

After adding the new User, clear it's properties.

As for your buttons, they should communicate with the ViewModel via Commands, which then only manipulate the collection itself using the simple Add and Remove methods it implements. You can learn more about it here

Hope this helps

Upvotes: 0

Nitin Purohit
Nitin Purohit

Reputation: 18580

Define a ObservableCollection property to be set a ItemsSource of DataGrid and update it when you want to add/delete any item from DataGrid. Updating the Collection will update the datagrid

        public MainWindow()
        {
            InitializeComponent();
            Users = new ObservableCollection<User>;
            Users.Add(new User() {Id = 101, Name = "gin", Salary = 10});
            Users.Add(new User() {Id = 102, Name = "alen", Salary = 20});
            Users.Add(new User() {Id = 103, Name = "scott", Salary = 30});

            dgsample.ItemsSource = Users;
        }

        private ObservableCollection<User> Users { get; set; }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            Users.Add(new User() {Id = int.Parse(tb1.Text), Name = tb2.Text, Salary = tb3.Text});
        }

Also, as a suggestion, the add/delete functionality is inbuild in DataGrid, setting CanUserAddRows and CanUserDeleteRows to true allows user to add item directly into the DataGrid, so you may not need your textboxes and button to add/delete

  <DataGrid AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True"></DataGrid>

Upvotes: 0

Related Questions