Net-informations.com
SiteMap  | About    

How to DataAdapter DataGridView - Sql Server

SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data is coming from. So the SqlDataAdapter manage the communication between these two Objects. The TableMapping Collections help the SqlDataAdapter to do this task.

The InsertCommand , the UpdateCommand , and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. The following C# source code demonstrate how to update a Dataset through SqlDataAdapter using a DataGridView . For running this C# source code , open a new C# project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.




using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        string connetionString;
        SqlConnection connection;
        SqlDataAdapter adapter;
        SqlCommandBuilder cmdBuilder;
        DataSet ds = new DataSet();
        DataSet changes;
        string Sql;
        Int32 i; 

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            connection = new SqlConnection(connetionString);
            Sql = "select * from Product";
            try
            {
                connection.Open();
                adapter = new SqlDataAdapter(Sql, connection);
                adapter.Fill(ds);
                connection.Close();
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                cmdBuilder = new SqlCommandBuilder(adapter);
                changes = ds.GetChanges();
                if (changes != null)
                {
                    adapter.Update(changes);
                }
                MessageBox.Show("Changes Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}




net-informations.com (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.