0

I am using WPF application in this form have one gridview and one button

i am using the ObservableCollection have Generic and one class code like this

public partial class MainWindow : Window
{
        public ObservableCollection<gm> data1 = new ObservableCollection<gm>();
        public MainWindow()
        {
            InitializeComponent();
        }
      //  public ObservableCollection<gm> data { get { return data1; } }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {

           data1.Add(new gm() { no = 2, name = "vipul" });
           dataGrid1.ItemsSource = data1.ToArray();
        }
    }
    public class gm
    {
        public int no { get; set; }
        public string name { get; set; }
    }
}

when i am execute above code it add blank row in datagrid please give me solution of this problem i want to know how to add row in datagird run time.

thanks in advance

vipul
  • 89
  • 2
  • 11

3 Answers3

0

set autogeneratecolumns to true and just set data1 as itemssource

xaml

 <DataGrid x:Name="dataGrid1" AutoGenerateColumns="True" />

EDIT: to get the power of WPF look into DataBinding/MVVM

blindmeis
  • 22,175
  • 7
  • 55
  • 74
0

XAML is like this:

<DataGrid ItemsSource="{Binding}" /> 

code behind is this:

public MainWindow()
{
    InitializeComponent();
    DataContext = data1;
}

and remove this line:

dataGrid1.ItemsSource = data1.ToArray();
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
0
 data1.Add(new gm { no = 2, name = "vipul" }); // Remore ellipsis around gm.

In XAML just check the following that

  1. You have DataSource of your datagrid to {Binding Path="data1"}
  2. DataColumn of no have binding to {Binding Path="no"}
  3. DataColumn of name have binding path to {Binding Path="name"}
Marshal
  • 6,551
  • 13
  • 55
  • 91