Click here to Skip to main content
15,937,779 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi..
i want to store datagrid(of wpf toolkit) data into database in wpf. i am using this code to cast datagrid to datatable..

DataTable dt = new DataTable();
dt = (DataTable)dataGrid1.ItemsSource;

it gives me error:
"Unable to cast object of type 'System.Collections.Generic.List to type 'System.Data.DataTable'."

how can i cast datagrid to datatable???

is there any other method to save data of datagrid to database?

thanks.
Posted

hello,
I have tried to solve this query in button1 i have binded the grid with data and in button 2 i whatever u edit in the grid and hit button2 those records will be saved in the database
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace updategrid
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ds = new DataSet();
        }
        DataSet ds;

        private void button1_Click(object sender, EventArgs e)
        {
            //binding grid to data from database
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=phonebook;Integrated Security=True");
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("select * from details", con); 
            adp.Fill(ds);
            DataTable dt = ds.Tables[0];
            dataGridView1.DataSource = dt;       
            con.Close();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //updating values in grid...
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=phonebook;Integrated Security=True");
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("select * from details", con); 
            SqlCommandBuilder build = new SqlCommandBuilder(adp);
            adp.Update(ds.Tables[0]);
            con.Close();
           
        }
    }
}


Do rate my answer once you find it useful

Thanks & Regards
Radix :)
 
Share this answer
 
v2
Go through this msdn post - it will give you a few ideas on how to achieve this.
 
Share this answer
 
Have a look at this article and a lot about WPF Datagrid and it's operations should be clear to you:
WPF DataGrid Practical Examples[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900