Tuesday 18 October 2016

c# dataset data adapter

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataAdapterDemo
{
    public partial class Form1 : Form
    {
        InventoryDB DB;
        public Form1()
        {
            InitializeComponent();

            //instantiate the data object
            DB = new InventoryDB();

            //bind the supplier table to the grid
            uxSuppliers.DataSource = DB.SupplierTable;
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DB.SaveChanges();
        }
    }
}

--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace DataAdapterDemo
{
    public class InventoryDB
    {
        private DataSet DB = new DataSet("Inventory");
        private SqlDataAdapter SupplierAdapter { get; set; }
        private string connectionString = 
            "server=localhost;database=Inventory;user id=sa;password=SQLPassword";

        public DataTable SupplierTable
        {
            get
            {
                return DB.Tables["Supplier"];
            }
        }

        public InventoryDB()
        {
            PopulateSupplierTable();

        }

        private void PopulateSupplierTable()
        {
            //instantiate the supplier adapter
            SupplierAdapter = 
                new SqlDataAdapter("SELECT * FROM Supplier", connectionString);

            //build the commands
            SqlCommandBuilder cb = new SqlCommandBuilder(SupplierAdapter);
            SupplierAdapter.InsertCommand = cb.GetInsertCommand();
            SupplierAdapter.UpdateCommand = cb.GetUpdateCommand();
            SupplierAdapter.DeleteCommand = cb.GetDeleteCommand();

            //fill the dataset
            SupplierAdapter.FillSchema(DB, SchemaType.Source, "Supplier");
            SupplierAdapter.Fill(DB, "Supplier");
        }

        public void SaveChanges()
        {
            SupplierAdapter.Update(DB.Tables["Supplier"]);
        }
    }
}

No comments:

Post a Comment