Ramji
Ramji

Reputation: 43

How to Add Rows to WPF dataGrid when "Add" button click?

Here am using the below code for adding rows to wpf datagrid,but if am again click to add means the row cannot be added and previous row replaced by new added details....So how to make possible to add new more rows based on add button click externally. Here the code a using ,its working for one row only added in datagrid,So how to make more new adding rows with externally button click.

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {

        DataTable dt = new DataTable();
        DataRow dr = dt.NewRow();
        if (!dt.Columns.Contains("Department"))
        {
            dt.Columns.Add("Department");
        }
        if (!dt.Columns.Contains("ScanTest"))
        {
            dt.Columns.Add("ScanTest");
        }
        if (!dt.Columns.Contains("Doctor"))
        {
            dt.Columns.Add("Doctor");
        }
        if (!dt.Columns.Contains("Date"))
        {
            dt.Columns.Add("Date");
        }
        if (!dt.Columns.Contains("Rate"))
        {
            dt.Columns.Add("Rate");
        }
        dr["Department"] = comboBox4.Text.ToString();
        dr["ScanTest"] = comboBox5.Text.ToString();
        dr["Doctor"] = comboBox6.Text.ToString();
        dr["Date"] = datePicker1.SelectedDate.Value;
        dr.ItemArray[0] = comboBox4.Text.ToString();
        dr.ItemArray[1] = comboBox5.Text.ToString();
        dr.ItemArray[2] = comboBox6.Text.ToString();

        dataGrid1.ItemsSource = dt.DefaultView;
        dt.Rows.Add(dr);
}

Upvotes: 0

Views: 4525

Answers (1)

bilal
bilal

Reputation: 658

Every time when you click the button a new Data Table is created and each time you add new single row in to it. Initialize the Data Table outside this function

DataTable dt = new DataTable(); //remove this line from button click

Upvotes: 2

Related Questions