Mahmoud Samy
Mahmoud Samy

Reputation: 439

How i can add new row into datagrid in wpf?

I'm trying to Insert all Rows values of DataGrid for Once every Click of a button , so if user inserted three times display on datagrid three rows,I have a class there is code

    public string Name { get; set; }
    public string Job { get; set; }
    public string Phone { get; set; }

    public MyGrid(string Vendors,string Jobs,string Tel)
    {
        Name = Vendors;
        Job = Jobs;
        Phone = Tel;
    }

and i called into button click event here

       static List<MyGrid> gride;
        gride = new List<MyGrid>();
        for (int i = 0; i < 3; i++)
        {
            var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
            gride.Add(myg1);

        }

        dataGridView1.ItemsSource = gride; 

this code it's working but there is the one problem,When add data is supposed to appear in a one row, but appears within 3 rows in the one click , I want to show one row in per click with different data . How i can add new row per click on the button in wpf

Upvotes: 1

Views: 6330

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81233

First of all this is not a way to do WPF way. Use proper bindings to achieve you want.

Steps to do in WPF way:

  1. Create ObservableCollection<MyGrid> and bind ItemsSource with that collection.
  2. Instead of setting ItemsSource again simply add object in that collection. DataGrid will be refreshed automatically since ObservableCollection implement INotifyCollectionChanged.

Now, for your code there are couple of issues.

  1. If you want item to be added once, why to run for loop and add object thrice. Remove the for loop.
  2. With every button click, you are re-initializing the list. Instead keep the list as instance field and initialize list only once from class constructor.
  3. No need to set ItemsSource again with every button click.

public class CodeBehindClass
{
   private ObservableCollection<MyGrid> gride;
   public CodeBehindClass()
   {
      gride = new ObservableCollection<MyGrid>();
      dataGridView1.ItemsSource = gride;
   }

   private void ButtonHandler(object sender, RoutedEventArgs e)
   {
      var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
      gride.Add(myg1);
   }
}

Upvotes: 2

Related Questions