1

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)
    {

    }
    }  
}

4 Answers 4

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

this.tb3.Text = currentUser.Salary.ToString();
can u expalin the code that u have written for the get_click event please
from the collection(users), i compare the Id value with tb1 TextBox, and get the correct index and assign to new User instance.finally get the the value from that instance.
0

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>

3 Comments

what is the error? you will need to add the namespace System.Collections.ObjectModel
Error The name 'users' does not exist in the current context i'm getting this
you dont have 'users' property it is 'Users'...change it
0

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

6 Comments

Error The type or namespace name 'ObservableCollection' could not be found (are you missing a using directive or an assembly reference?)
Error The name 'users' does not exist in the current context
Add the following using statement using System.Collections.ObjectModel;
did you define Users as a public property in your ViewModel? where are you trying to access it from?
@user2889489 Update your question with the updated code and the error's you are getting. We can't help you without understanding what you are doing ...
|
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.