Insert, Update, Delete with DataGridView Control in C# (Windows Application)

DataGridView control is one of the coolest features of Dot Net Framework. You can use this control in Windows Form using Wizard or programmatically.

Add a DataGridView control and two Buttons on a Form. One Button is for deleting the selected row and other one is for updating or inserting new row.

Declare those variables as shown below.



public partial class DataTrialForm : Form
    {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataTrialForm()
        {
            InitializeComponent();
        }

In the Form Load event set data source for the DataGridView control.



private void DataTraiForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            selectQueryString = "SELECT * FROM t_Bill";

            sqlConnection.Open();

            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

            dataGridViewTrial.DataSource = bindingSource;
            
            // if you want to hide Identity column
            dataGridViewTrial.Columns[0].Visible = false;
        }

To update, insert or delete data in database from DataGridView have a look at this code snippet.



private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }


        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
               dataGridViewTrial.Rows.RemoveAt(dataGridViewTrial.CurrentRow.Index);
               sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
               MessageBox.Show(exceptionObj.Message.ToString());
            }
        }


Download Source Code and start exploring DataGridView control.

Thanks
A Rahim Khan

About these ads
  1. Thanks Rahim ur awesome.
    i got tired of searching how to fill/update/delete datagridview.
    Finally i found ur post it’s worked for me.
    Thanks a lot n keep posting good articles…

    Thanks and Regards,
    K. Ganesh Kumar
    Software Developer

    • Thanks for your appreciation.

        • AQUEELHASHMI
        • January 13th, 2012

        SIR MY PROBLEM IS WHEN I UPDATE COLUM IN GRIDVIEW THAN EXEPTION ARISE NO METHOD OVERLOD
        MY COD IS: {
        this.dataTable1TableAdapter1.InsertQuery(Convert.ToDateTime(dateTimePicker1.Text),
        Convert.ToInt16(textBox3.Text), textBox4.Text, textBox5.Text,
        textBox6.Text, Convert.ToDouble(textBox7.Text), Convert.ToDouble(textBox8.Text),
        Convert.ToDouble(textBox9.Text), radioButton1.Checked, radioButton2.Checked, radioButton3.Checked);
        this.dataTable1TableAdapter1.Fill(this.database1DataSet.DataTable1);
        }
        }

        • Gajanan
        • January 25th, 2012

        I want code in 3 tire Architecture ….plz send me code

      • attamh gowwill
      • March 12th, 2011

      very good. can you please design a user interface and connect to database usnig ling or ado.net

      • suresh
      • December 28th, 2011

      hi.. my dear friend how to search the data in grid view form the database. please send the code to my mail id suri1319@gmial.com

    • Pawan
    • October 20th, 2010

    Hi dear
    how r u i wand the code of update and save button in windows form and when i select in datagridview then the selected value will show in text box

    • hey, you have to write code at Cell Click Event. This will be something like…(please check out code syntax)

      Integer i = DataGridView1.CurrentRow.Index;
      TextBox1.Text = DataGridView1.Item(0, i).Value;
      TextBox2.Text = DataGridView1.Item(1, i).Value;
      TextBox3.Text = DataGridView1.Item(2, i).Value;
      TextBox4.Text = DataGridView1.Item(3, i).Value;

      Now, at your Button Click Event, you can save those TextBox values in Database.

        • Md. Arefin Hasan Bhuiyan
        • August 20th, 2011

        Here is another way. DataGridview have a Rowheadermouse click event.. by we can select value to the Label or textbox or any where.

      • One more better way to do this is using
        DataGridView1[“Column Name”,e.rowIndex).Value in CellClick event of DataGridView.

        Benift of this is if the sequence of Columns changes, the o/p will not effect.

    • thanks.

      quite easy and neat code.,

      can u plz. tell me how can i use inner join in asp.net
      for inserting records. its urgent. plz.

    • Mauricio
    • October 22nd, 2010

    hi
    I try update , insert with datagridview

    field autonumber, i can’t this..

    any help?

    • you don’t have to worry about auto number or identity column. you can hide it in DataGridView in this way.

      // if you want to hide Identity column
      dataGridViewTrial.Columns[0].Visible = false;

      Or you can make it read only column.

    • roshan
    • November 17th, 2010

    thanks,,buddy u r great………

    • CHAUHAN
    • January 4th, 2011

    Thanks Rahim, just want to update, insert,delete and save the data from one form in C# with SQL Server2005 in windows applications. Can you help me out???

    • Rishabh
    • January 26th, 2011

    thank u much … its working !!

    • Priya
    • February 28th, 2011

    hello..

    nice code.. thanx it helps me..
    i wans to ask if there any code for datagridview using three tier architecture
    thanx in advance.. pls reply

  2. Now please provide me code .
    if we want to insert all data of datagridview into database via one click
    how i loop through datagridview.

    • foreach(var row in DataGrid1.Rows)
      {
      DoStuff(row);
      }

      foreach(DataGridRow row in DataGrid1.Rows)
      {
      DoStuff(row);
      }

      for(int i = 0; i< DataGrid1.Rows.Count – 1; i++)
      {
      DoStuff(DataGrid1.Rows[i]);
      }

      • foreach(var row in DataGrid1.Rows)
        {
        DoStuff(row);
        }

        foreach(DataGridRow row in DataGrid1.Rows)
        {
        DoStuff(row);
        }

        for(int i = 0; i< DataGrid1.Rows.Count – 1; i++)
        {
        DoStuff(DataGrid1.Rows[i]);
        }

        above code is not so clear please

        dostuff(row) do stuff(column)

        take an example we have 3 column

        product_name product_quatity product_price
        parle g 3 12
        crackjack 3 23
        50-50 3 21

        now please make this thing happen to your provide code so that i can use this loop u provide me.

    • Sophia
    • June 15th, 2011

    hih
    saw your post, it really great, but if i have web service, how am i going to call the web service web method to the datagridview and do the update, insert and delete???cause i am only am be to retrieve the data to the datagridview
    for delete, i want to delete in the datagridview, meaning each row got it own delete button
    please provide me with the code…..

  3. Hi Rahim,
    This is Khurshid here, i am developing a accounting software like tally, but i dont know how to save data in text file, can you help to sort-out this problem.

    • Ankita
    • July 6th, 2011

    Thank you Rahim , it’s too useful to me.

    • shilpa
    • July 11th, 2011

    hi Rahim,
    Thanks a lot for the code…
    it helped me alot!!
    God bless you…

    • Shaon
    • July 18th, 2011

    Bhaia,
    thanks,it was really useful to me.
    data is showing accurately while form load. but in button click event for update, its showing an error. which is:

    Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

    NOW WHAT? plz help me out.

    • You don’t have any key(primary) in the selected rows. modify your select statement.

        • Shaon
        • July 19th, 2011

        Thanks bhaia,
        I have created one column ‘cust_ID’ primary key in DB. Now its working perfectly.
        But i tried to use a textbox in the form where i will give a customer_ID and also a button. So, if i click the button then it will show the result in DataGrid, against the customer_ID which will be given in the textbox. For this, i used where condition in the query and left the rest of the code as before(similar to urs). But unfortunately its not working. Its showing the Column Headers but no result.
        help me out again…
        :-)

    • Karthic
    • July 19th, 2011

    Hello Rahim ..,

    I’m new to windows application n my coding here is C# ..,,

    I want to perform Edit , Delete n Update in dataGridView n data should b saved in DB ,, Used Ur code bt the update so far don in GRIDVIEW only and its nt saved in DB .., It is very easy to perform Update Delete in WEB Application ..,, Bt here it is hectic ..,, Want to complete the task ..,, Help m out of it ..,, Hoping for a reply soon !!

    Thanks,,
    Karthic.

    Here is the following code that i did n nt effective !!

    namespace Database
    {
    public partial class Form6 : Form
    {
    private SqlDataAdapter da;
    private SqlConnection conn;
    BindingSource bsource = new BindingSource();
    DataSet ds = null;
    string sql;

    public Form6()
    {
    InitializeComponent();

    // if you want to hide Identity column
    dataGridView1.Columns[0].Visible = false;

    LoadData();

    // if you want to hide Identity column
    //dataGridView1.Columns[0].Visible = false;

    panel2.Visible = false;

    }

    public void LoadData()
    {
    string connectionString = @”Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database2.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”;
    conn = new SqlConnection(connectionString);
    sql = “SELECT MemberName,RollNumber,Designation,DOB,Month,DOJBank,DOJBranch,BranchCode,BranchName,LFCAvailed,LFCNext,LFCOPtions,MobileNumber,Remarks FROM DBstore”;

    da = new SqlDataAdapter(sql, conn);
    conn.Open();
    ds = new DataSet();
    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
    da.Fill(ds, “DBstore”);
    bsource.DataSource = ds.Tables["DBstore"];
    dataGridView1.DataSource = bsource;

    }

    //public void Bind()
    //{
    // SqlConnection Cn = new SqlConnection(“Data Source=.;Initial Catalog=master;Integrated Security=True”);
    // Cn.Open();
    // SqlDataAdapter Adt = new SqlDataAdapter(“select * from DBstore”, Cn);
    // SqlCommandBuilder commandBuilder = new SqlCommandBuilder(Adt);
    // DataTable Dt = new DataTable();
    // Dt.Locale = System.Globalization.CultureInfo.InvariantCulture;
    // Adt.Fill(Dt);
    // dataGridView1.DataSource = Dt;
    // //bindingSource1.DataSource = table;
    // //dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

    // // if you want to hide Identity column
    // //dataGridView1.Columns[0].Visible = false;

    // Cn.Close();

    //}

    private void button2_Click(object sender, EventArgs e)
    {
    //SqlConnection Con = new SqlConnection(“Data Source=.;Initial Catalog=master;Integrated Security=True”);
    //Con.Open();

    //try
    //{
    // for(int i= 0; i 0)
    // {
    // DialogResult result = MessageBox.Show(“Are you sure you want to proceed in Updation ?”, “Confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    // if (result == DialogResult.Yes)
    // {
    // string A = dataGridView1.Rows[i].Cells["E_ID"].Value.ToString();
    // string MemberName = dataGridView1.Rows[i].Cells["MemberName"].Value.ToString();
    // string RollNumber = dataGridView1.Rows[i].Cells["RollNumber"].Value.ToString();
    // string Designation = dataGridView1.Rows[i].Cells["Designation"].Value.ToString();
    // string DOB = dataGridView1.Rows[i].Cells["DOB"].Value.ToString();
    // string DOJBank = dataGridView1.Rows[i].Cells["DOJBank"].Value.ToString();
    // string DOJBranch = dataGridView1.Rows[i].Cells["DOJBranch"].Value.ToString();
    // string CommencedLTA = dataGridView1.Rows[i].Cells["CommencedLTA"].Value.ToString();
    // string NextLTA = dataGridView1.Rows[i].Cells["NextLTA"].Value.ToString();
    // string AvailLTA = dataGridView1.Rows[i].Cells["AvailLTA"].Value.ToString();
    // string Remarks = dataGridView1.Rows[i].Cells["Remarks"].Value.ToString();

    // SqlCommand Cmd = new SqlCommand(“Update DBstore set as MemberName ='” + MemberName + “‘, RollNumber ='” + RollNumber + “‘, Designation ='” + Designation + “‘, DOB ='” + DOB + “‘, DOJBank ='” + DOJBank + “‘, DOJBranch ='” + DOJBranch + “‘, CommencedLTA ='” + CommencedLTA + “‘, NextLTA ='” + NextLTA + “‘, AvailLTA = ‘”+AvailLTA+”‘, Remarks = ‘” + Remarks + “‘ where A ='” + E_ID + “‘)”, Con);
    // //Cmd.CommandText = ;
    // Cmd.ExecuteNonQuery();
    // Con.Close();
    // Bind();

    // MessageBox.Show(“Recorded Updated Successfully”);

    // }
    // }
    // }
    // }
    //}

    //catch (Exception exceptionObj)
    // {
    // MessageBox.Show(exceptionObj.Message.ToString());
    // }

    //try
    //{
    // sqlDataAdapter.Update(dataTable);
    // Bind();
    //}
    //catch (Exception exceptionObj)
    //{
    // MessageBox.Show(exceptionObj.Message.ToString());
    //}

    try
    {
    DialogResult result = MessageBox.Show(“Are you sure you want to proceed Updation ?”, “Update Confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (result == DialogResult.Yes)
    {
    SqlConnection CN = new SqlConnection(@”Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database2.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”);
    CN.Open();

    string query = “Select * from DBstore”;

    SqlDataAdapter dAdapter = new SqlDataAdapter(query, CN);

    SqlCommandBuilder cBuilder = new SqlCommandBuilder(dAdapter);

    DataTable dTable = new DataTable();

    dAdapter.Fill(dTable);

    DataGridView DGview = new DataGridView();

    BindingSource bSource = new BindingSource();

    DGview.DataSource = bSource;

    //dataGridView1.DataSource = bSource;

    dAdapter.Update(dTable);

    //DataTable dt = ds.Tables["DBstore"];
    //this.dataGridView1.BindingContext[dt].EndCurrentEdit();
    //this.da.Update(dt);
    CN.Close();

    }
    else
    {

    }

    }
    catch (Exception exceptionObj)
    {
    MessageBox.Show(exceptionObj.Message.ToString());
    }

    }

    private void button3_Click(object sender, EventArgs e)
    {
    try
    {
    DialogResult result = MessageBox.Show(“Are you sure you want to delete this row?”, “Delete confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
    foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
    {
    if (dataGridView1.Rows.Count > 1)
    dataGridView1.Rows.Remove(dr);
    }
    }

    //DialogResult result = MessageBox.Show(“Are you sure you want to proceed in Updation ?”, “Confirmation”, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    //if (result == DialogResult.Yes)
    //{
    // DataGridViewRow Row = dataGridView1.Rows[e.GetType];
    // Label E_ID = (Label)Row.GetType(“E_ID”);
    // int EID = Convert.ToInt32(E_ID.Text);
    // Cn.Open();
    // SqlCommand Cd = new SqlCommand(“Delete from DBstore where E_ID=” + E_ID.Text + “”, Cn);
    // Cd.ExecuteNonQuery();
    // Cn.Close();
    // dataGridView1.Rows.Remove(EID);
    //}
    //else
    //{
    // foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
    // {
    // if (dataGridView1.Rows.Count > 1)
    // dataGridView1.Rows.Remove(dr);
    // }
    //}
    }
    catch (Exception exceptionObj)
    {
    MessageBox.Show(exceptionObj.Message.ToString());
    }

    ////try
    ////{

    //// dataGridView1.Rows.Remove(dataGridView1.CurrentRow);

    //// sqlDataAdapter.Update(dataTable);

    // //DataGridViewRow Row = dataGridView1.Rows[E_ID];

    // //SqlConnection Con = new SqlConnection(“Data Source=.;Initial Catalog=master;Integrated Security=True”);
    // //Con.Open();
    // //SqlCommand cd = new SqlCommand(“Delete from Phase2 where E_ID=” + + “”, Con);
    // //cd.ExecuteNonQuery();
    // //Con.Close();

    // //dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
    // //sqlDataAdapter.Update(dataTable);

    // //Bind();
    //}
    //catch (Exception exceptionObj)
    //{
    // MessageBox.Show(exceptionObj.Message.ToString());
    //}
    }

    private void Form6_Load(object sender, EventArgs e)
    {
    // TODO: This line of code loads data into the ‘masterDataSet.DBstore’ table. You can move, or remove it, as needed.
    //this.dBstoreTableAdapter.Fill(this.masterDataSet.DBstore);

    // if you want to hide Identity column
    dataGridView1.Columns[0].Visible = false;

    LoadData();

    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
    panel2.Visible = true;

    SqlConnection CN = new SqlConnection(@”Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database2.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”);
    //selectQueryString = “select * from DBstore where RollNumber='” + textBox1.Text + “‘”;

    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(“select * from DBstore where RollNumber='” + textBox1.Text + “‘”, CN);
    SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

    DataTable dataTable = new DataTable();
    sqlDataAdapter.Fill(dataTable);
    BindingSource bindingSource = new BindingSource();

    bindingSource.DataSource = dataTable;

    dataGridView1.DataSource = bindingSource;

    // if you want to hide Identity column
    dataGridView1.Columns[0].Visible = false;

    clear();
    }

    private void button4_Click(object sender, EventArgs e)
    {
    panel2.Visible = false;
    }

    public void clear()
    {
    textBox1.Text = ” “;
    }
    }
    }

    • Hello Karthic

      In the sample project I Updated DB at Buttoin Click Event using the following code snippet.

      private void addUpadateButton_Click(object sender, EventArgs e)
      {
      try
      {
      sqlDataAdapter.Update(dataTable);
      }
      catch (Exception exceptionObj)
      {
      MessageBox.Show(exceptionObj.Message.ToString());
      }
      }

        • Karthic
        • July 21st, 2011

        Thanq so much for ur reply ..,,

        Here throws another exception if i use Ur code given ..,

        Dynamic SQL Generation for the update command is not supported against a select command that doesn’t return any key column information ..,,

      • you do’nt have any primary key in selected rows.

        On Thu Jul 21st, 2011 5:34 PM BDST

        • Karthic
        • August 2nd, 2011

        Yeah Rahim ..,, ThanQ so much ..,, The Update n Delete is working now ..,, As i use SQL Database ..,, I didn set a primary key ..,,

    • Shaon
    • July 20th, 2011

    solved….it was my mistake..

    • seradni
    • July 24th, 2011

    Please i wanna know the method delete and thanks 4 ur effort

    • Shaon
    • July 30th, 2011

    Bhaia,
    I have done Insert,Update,Delete in dataGridView in the same way as urs.
    But now i want to take a dataGridView where i will add 3 column(name,address,Phone) manualy. Is it possible to do the same things(insert,update,delete) with database in this Gridview. how ??
    all i know is that: i have to bind it with object. but how?

    • Karthic
    • August 2nd, 2011

    Update for the entire row is happening ..,, But for a single column it throws an exception ..,, Can U sort out this problem .. Delete is also not working properly ..,, There also throws an exception ..

    Thanx in advance :)

  4. Hello Rahim,

    I am C# windows fresher, please suggest me how can i make projects and what should i do for established my career in software development in c#????

    • hameed
    • August 24th, 2011

    Shukriyaaa Rahim bhaiiiiii………………………………

  5. update and delete and working fine, but i want insert the data from grid to sql table. please help me ragarding inserting the data…

    • Please have a look at this addUpadateButton_Click Event code.

      private void addUpadateButton_Click(object sender, EventArgs e)
      {
      try
      {
      sqlDataAdapter.Update(dataTable);
      }
      catch (Exception exceptionObj)
      {
      MessageBox.Show(exceptionObj.Message.ToString());
      }
      }

      Now, whatever you do with the datagridview like insert or update on the form this will update or insert in to database accordingly.

      Thanks

  6. hi rahim,I have a problem to retrieve image from ms access database into picture box through c#code,can u resolve my problem!

    Thanks in advance.

    • urmila
    • August 31st, 2011

    i am a new user of vb.net . i have a problem with insert image in database .i create my form in .net windows application.

    • Sanjay Patel
    • September 1st, 2011

    hey dude ConfigurationManager is didnt work here…in insert update application..I write it in gridview event…

    • Configuration Manger will only work if you add reference of System.Configration to your project.

  7. Hi,

    I m facing the problem in using the configurationManager,so plz tell me that i have to use any namespace or i miss some code when i m using your code in datagridview.

    Regards
    Arpan

    • You will have to add reference of System.Configuration (most probably ) to your project. To get clear idea download this project from this page.

      • Dear Sir,
        how can i add the reference of system.configuration, i m unable to ignore this error if u have time to solve my problem then reply step by step i have download code but no success to remove the errror.
        Regards,
        Arpan

      • To add a reference in Visual C#
        # In Solution Explorer, right-click the project node and click Add Reference.
        # In the Add Reference dialog box, select the tab indicating the type of component you want to reference.

        Select the components you want to reference, and then click OK.

        *****in your add reference to System.Configuration.dll.

        
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Configuration;
        
        namespace Utility
        {
            public class CommonVariables
            {
                public static String ConnectionString
                {
                    get { return ConfigurationManager.ConnectionStrings["EmployeeEntities"].ConnectionString; }
                }  
            }  
        }
        

        Hope this will work out your problem.

    • Dev
    • September 5th, 2011

    i want to generate confirmation box after inserting records in database in asp.net C#

    • please refer to link for confirmation in Gridview.

      http://khanrahim.wordpress.com/2010/07/08/delete-confirmation-in-asp-net-gridview/

      However, for Button Click (on client click) write client confirmation javascript code.

        • Gaurav chhabra
        • September 8th, 2011

        Hello Rahim,

        Thanks for your code for update from Grid view to database…. But unfortunately when i debugging this code an error is coming ” System.Data.DataTable’ is a ‘type’ but is used like a ‘variable’ ”
        can you please suggest that how can i improve that…….

    • kartik
    • September 19th, 2011

    Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information……….When i click update button i got this exception can u tell me why???

    • without key column information, you will not get update/delete working in datagridview

    • Mittai Kariss
    • September 20th, 2011

    thanks bro…..

    i have finished delete and update but i have some logical errors….but now i refered ur code.now clear that error..thanks a lot..

  8. hi bro..

    i have one doubt…

    my first form is datagridview …side buttons is..add ,edit, delete,and close…now i want add some details then click add button then open another form…..now insert the data from add form….now add form close after inserted data…..i want automatic refresh the form1……

    i am using form1 obj=new form1();
    obj.refresh();

    but it is not work….
    how do that….?

    • this will not work. When you click add button , close the datagrid form, open up the add data form. Now, when you close the add data form, open the datagrid form again automatically. I have done this kind of stuffs with vb6, has not done it with C#. it should work somehow.

      • Nisha
      • October 14th, 2011

      give obj.show();

  9. the better idea is create a new function in datagridform, then shift(cut & paste) the code which you use to fill datagridview in a new function(means refactor the code to function).
    Now when you close the add form call that function.

    In case you are adding row by row, then clear the rows of datagridview first in the function

    • pulasthi
    • September 21st, 2011

    thankx bor thats what i want… searching searching… at last i found you man.. thankx one again…

    • satish
    • September 21st, 2011

    Hi,This is satish

    I have one doubt please help me.imwriting the code like this

    int i = Convert.ToInt16(dataGridView1.SelectedRows.Count.ToString());
    for (i = 0; i <= 10; i++)
    {
    //int i = Convert.ToInt16(dataGridView1.SelectedRows.Count.ToString());
    string Sno = dataGridView1.SelectedRows[i].Cells[0].Value.ToString();
    string name = dataGridView1.SelectedRows[i].Cells[1].Value.ToString();
    string amount = dataGridView1.SelectedRows[i].Cells[2].Value.ToString();

    con = new SqlConnection("user id=sa;password=sa;database=Test;data source=.");
    con.Open();
    cmd = new SqlCommand("delete from t1 where Sno='" + Sno + "' and name='" + name + "' and amount='" + amount + "'", con);
    cmd.ExecuteNonQuery();
    con.Close();

    }
    how to delete multiple rows

    • satish
    • September 21st, 2011

    How we can access the entry’s in another system using LAN while running software in both systems. How to write the connection string to that in windows application(C#).

    Im writing code like this

    connectionString = “Data Source=10.1.2.16.1433;database=Northwind;User
    ID=sa;Password=sa”;

    but Sql server2005 error shows like :SQL Server doesn’t allow remote connections.

    can u send sample code for that.
    THANQ………

    • satishKumar
    • September 21st, 2011

    Hi,

    How to print the grid items with single click of Printbutton for C# windows application Without using Crystal reports.

  10. hello..
    i want to add, delete, update in my C# forms through DLL… adding , deleting , updating textboxes is very simple if we write codes on buttons. but i want to learn that how we doing this through DLL. plz share some knowledge with me..

    thanx in advance..

    • vivek
    • September 26th, 2011

    got this error on clicking the update and delete button:

    Update requires a valid delete command when passed DataRow collection with deleted rows

  11. Hi… Thanks so much :)
    please help me, how I can deal with foreign key in datagridview???
    how I can get it in datagridview and connect two tables…?

  12. This is really helpful. Explains the thing clearly. Thanks a lot.

    • thenndral
    • October 4th, 2011

    Hi,

    I first thank you such a wonderful code.

    you use single table insert/update/delete. I want to know how to insert/update/delete in a Multiple tables in a single datagridview.

    can you give me an example?

    thanks
    thendral

      • Raman Kumar
      • October 6th, 2011

      HI Rahim,

      My Name is Raman ,as per the above comments , I understand you are very good at .net
      I am new to win app, but good SQL server,
      Can you tell me , I Can Solve the below querdy.

      I have 5 tables and one datagridview , which display the information from 5 different tables,
      now user is allowed add/update/delete opration in the grid with new information.
      user can add or update or delete the datagridview row.
      I have single button “SAVE” which save the data in the database. how can i set , update or insert or delete operation on one “SAVE” button.

      • Hello Raman

        I have not used datagridview with multiple tables for inserting, updating, deleting records. i will look into this ASAP and will let you know hopefully.

        • JanOlMajti
        • January 17th, 2012

        I have similar problem

    • NoMoreHeadaches
    • October 6th, 2011

    Thank you for this great example, after hours of trying to find a way to do this your example was nice and clean to read and understand. I can now breathe easier. Haha!

    • ABC
    • October 15th, 2011

    GOOD WORK ..THNKS FOR SAVING TIMIng

    • siva
    • October 18th, 2011

    hi

    • siva
    • October 18th, 2011

    Hi Rahim,

    First of all thanks for such a code,because i researched the entire google but found no single code for this ins,upd & del.Now i just have a doubt,i used part of ur code to do just a delete opr in datagridview.when i update the database,it keeps on giving the same error that,”Object reference not set to instance of an object.NullReferenceException”.Am getting mad trying alternatives for this error for 2 days.pls help resolve.
    here it is:

    • siva
    • October 18th, 2011

    public partial class Form3 : Form
    {
    SqlConnection sqlConnection = null;
    string sqlQuery=null;
    SqlDataAdapter sqlDataAdapter = null;
    DataTable dataTable = null;
    SqlCommandBuilder sqlCommandBuilder = null;
    BindingSource bindingSource = null;

    public Form3()
    {
    InitializeComponent();
    }

    private void Form3_Load(object sender, EventArgs e)
    {
    SqlConnection sqlConnection=new SqlConnection(“Data Source=SHANKSUDA\\SQLEXPRESS;Initial Catalog=shanks;Integrated Security=True”);
    sqlQuery=”select * from shankstb1″;
    sqlConnection.Open();
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, sqlConnection);
    sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
    dataTable = new DataTable();
    sqlDataAdapter.Fill(dataTable);
    bindingSource = new BindingSource();
    bindingSource.DataSource = dataTable;
    dataGridView1.DataSource = bindingSource;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
    dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
    bindingSource.EndEdit();
    sqlDataAdapter.Update(dataTable);
    }

    Am getting the exception pointing at
    sqlDataAdapter.Update(dataTable);

    Thanks in advance,
    siva

    • siva
    • October 18th, 2011

    Sorry my comment wasn’t getting posted together,so had to split it.

    • pankaz kumar
    • October 21st, 2011

    Sir…how i can update & refresh table i database through form load page ….i wanted to do it by one click on form…plz giv me code…..

  13. THank you vai… it was very interesting and help full for me…

    • Aatif Rahman
    • November 2nd, 2011

    Salam bhai,
    I’ve done each and every step as you told here..but still i am getting an error as”The name ‘ConfigurationManager’ does not exist in the current context” but i am getting an option of “configuration setting”..when am trying to run with that there’s a run time error as “sql exception was unhandled”..I wanna use my own Database here..please help..
    regards,
    Aatif.

    • rahul
    • November 9th, 2011

    sir ,
    how to display data from two tables in the form of gatagrid.
    my two tables are…personal and placement1.

    in personal the attributes are usn,name,batch,address.
    in placement1 the attributes are usn,company,year.

    i just want to retrieve the data which will contain usn,name,batch,company,year.

    i m using visual studio 2008 express edition and sql server 2005.
    my project is windows form based application using only c#.

    • rishi
    • November 18th, 2011

    hello sir

    i am making my gridview in window form when i update my colum value
    this type of message i am getting.
    message—“Dynamic sql generation for the update command is not supported against a select command that does not return any key colum information”

    pls give me solution

    • Anand
    • November 18th, 2011

    return ConfigurationManager.ConnectionStrings["EmployeeEntities"].ConnectionString;

    connection string gives error…..”ConfigurationManager does not exist”

  14. // There is a problem in code .. i m not able to view the data through datagridview kindly help me out..
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;

    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    namespace CheckConn
    {
    public partial class pescontact : Form
    {
    public string n1;
    // public string pas2;
    public string con
    {
    set
    {
    n1 = value;
    }
    get
    {
    return n1;
    }
    }
    public pescontact()
    {
    InitializeComponent();
    }

    private void pescontact_Load(object sender, EventArgs e)
    {
    // TODO: This line of code loads data into the ‘database1DataSet1.contact’ table. You can move, or remove it, as needed.

    // TODO: This line of code loads data into the ‘database1DataSet1.contact’ table. You can move, or remove it, as needed.
    //
    // TODO: This line of code loads data into the ‘database1DataSet2.contact’ table. You can move, or remove it, as needed.

    tableLayoutPanel1.Visible = true;
    tableLayoutPanel3.Visible = false;
    button1.Enabled = true;
    button3.Enabled = true;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
    textBox4.Text = con;
    try
    {
    string path = “Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\sanghati\\My Documents\\Visual Studio 2010\\my project\\Pes mail server\\CheckConn\\CheckConn\\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”;
    SqlConnection conn = new SqlConnection(path);
    conn.Open();
    string q = “INSERT INTO contact (add_frm,con_name,addr,mail_id,mob ) ” + “VALUES (‘” + textBox4.Text + “‘, ‘” + textBox1.Text + “‘, ‘” + richTextBox1.Text + “‘,'” + textBox2.Text + “‘,'” + textBox3.Text + “‘) “;
    SqlCommand cmd = new SqlCommand(q, conn);

    SqlDataReader dr = cmd.ExecuteReader();

    //dataGridView1.Refresh();
    conn.Close();
    MessageBox.Show(“The contact of ” + textBox1.Text + “has been added”);
    }
    catch (Exception d)
    {
    MessageBox.Show(d.Message);
    }
    }

    private void button2_Click(object sender, System.EventArgs e)
    {
    tableLayoutPanel1.Visible = true;
    tableLayoutPanel3.Visible = false;
    textBox1.Text = ” “;
    textBox2.Text = ” “;
    textBox3.Text = ” “;
    richTextBox1.Text = ” “;
    if (textBox1.Focus())
    {
    button1.Enabled = true;

    }
    button2.Enabled = false;

    }

    private void button3_Click(object sender, System.EventArgs e)
    {
    dataGridView1.Refresh();
    tableLayoutPanel3.Visible = true;
    tableLayoutPanel1.Visible = false;
    button1.Enabled = false;
    button4.Enabled = true;
    button2.Enabled = true;
    // this.contactTableAdapter.Fill(this.database1DataSet1.contacts);
    /// this.contactTableAdapter2.Fill(this.database1DataSet1.contact);
    //this.contactTableAdapter2.Fill(this.database1DataSet11.contact);

    string path1 = “Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\sanghati\\My Documents\\Visual Studio 2010\\my project\\Pes mail server\\CheckConn\\CheckConn\\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”;
    SqlConnection conn = new SqlConnection(path1);
    conn.Open();
    string r = “select add_frm,con_name,addr,mail_id,mob from contact where add_frm='” + con + “‘;”;
    Database1DataSet ds = new Database1DataSet();

    SqlDataAdapter dAdapter = new SqlDataAdapter(r, conn);
    //Database1DataSet ds = new Database1DataSet();
    // dataGridView1.Refresh();
    dAdapter.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
    //dataGridView1.DataSource = ds.Tables[1];
    //dataGridView1.DataSource = ds.Tables[2];
    dataGridView1.Columns[0].HeaderText = “FROM”;
    dataGridView1.Columns[1].HeaderText = “NAME”;
    dataGridView1.Columns[2].HeaderText = “ADDRESS”;
    dataGridView1.Columns[3].HeaderText = “EMAIL ID”;
    dataGridView1.Columns[4].HeaderText = “MOBILE NUMBER”;
    dataGridView1.Columns[5].HeaderText = ” “;
    //dataGridView1.DataSource = ds.Tables[3];
    // dataGridView1.DataSource = ds.Tables[4];
    // dataGridView1.DataSource = ds.Tables[5];

    dAdapter.Update(ds);
    }

    private void button4_Click(object sender, System.EventArgs e)
    {
    string path1 = “Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\sanghati\\My Documents\\Visual Studio 2010\\my project\\Pes mail server\\CheckConn\\CheckConn\\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True”;
    SqlConnection conn = new SqlConnection(path1);
    conn.Open();
    string up = “DELETE FROM contact where add_frm ='” + con + “‘;”;
    Database1DataSet ds = new Database1DataSet();
    SqlDataAdapter dAdapter = new SqlDataAdapter(up, conn);
    dAdapter.Fill(ds);
    // BindingSource bs = new BindingSource();
    //dataGridView1.DataSource = bs;
    // dataGridView1.Columns[0].Visible = true;
    try
    {
    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);

    dAdapter.Update(ds);

    dataGridView1.Refresh();
    }
    catch (Exception exceptionObj)
    {
    // MessageBox.Show(exceptionObj.Message.ToString());
    }
    }

    private void button5_Click_1(object sender, EventArgs e)
    {
    this.Close();

    }

    /* private void fillByToolStripButton_Click(object sender, EventArgs e)
    {
    try
    {
    this.contactTableAdapter3.FillBy(this.database1DataSet2.contact);
    }
    catch (System.Exception ex)
    {
    System.Windows.Forms.MessageBox.Show(ex.Message);
    }

    }*/

    }
    }

  15. how to display datagridview control in c sharp .net?

    • rob
    • November 25th, 2011

    I got table which is relation table for two another tables, so i got there only 2 columns with foreign key numbers and 1 column with value. Is possible to change some numbers in some columns to names from another table?

    • Dipika
    • November 28th, 2011

    Hello A Rahim ,
    ur post is really good for every Developer.

    • sudheep
    • December 1st, 2011

    Hi,
    I am having two tables they are tbl_report1,tbl_report2.the columns
    Tbl_report1 columns:
    Invoiceno,particulars,quantity,perprice,amount,invoicedate,ondate,invoiceid,orderno
    Tbl_report2 columns:
    Compname,compaddress,invoiceno,orderno,ondate,invoicedate,amountstatus,netamount,netvat,tamount
    Tbl_customer columns:
    Custid,custname,custaddress,custcity,custstate,custstdcode,custphoneno,custmobileno
    How can I combine these two tables
    .in my form I am having these fields like I mentioned above two tables.my issue is if I select the compname it should display the remaining fields.for loading only companynames I wrote the code is below.
    private void loadcompanies()
    {
    SqlConnection con = new SqlConnection(“data source=mars-104;initial catalog=marsweb;integrated security=true”);
    SqlCommand cmd = new SqlCommand(“select ‘0’ as compaddress,’selectone’ as compname union select compaddress,compname from dbo.tbl_report2 “, con);//I am using here customer table.for this reason only it shows customer address itself.can you please correct this for getting all fields.
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    if (con.State == ConnectionState.Closed)
    {
    con.Open();
    }
    da.Fill(dt);
    cmb_companyname.DataSource = dt;
    cmb_companyname.DisplayMember = “compname”;
    cmb_companyname.ValueMember = “compaddress”;
    }
    But it shows the customeraddressonly.for that I wrote the code in selectedindexchangedevent.
    private void cmb_companyname_SelectedIndexChanged(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(“data source=mars-104;initial catalog=marsweb;integrated security=true”);
    SqlCommand cmd = new SqlCommand(“select t2.compaddress,t1.invoiceno,t1.orderno,t1.ondate,t1.particulars,t1.perprice,t1.amount,t2.netvat,t2.tamount,t2.netamount from tbl_report2 t2,tbl_report1 t1 where t1.compname=’hdfcbank’ and t2.compname=’hdfcbank'”, con);
    //SqlCommand cmd = new SqlCommand(“select custaddress from tbl_customer where custname=@custname”, con);
    //cmd.Parameters.AddWithValue(“@custname”,cmb_companyname .Text );
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    txt_customeraddress.Text = cmb_companyname.SelectedValue.ToString();
    //txt_orderno.Text = cmb_companyname.SelectedValue.ToString();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
    txt_customeraddress .Text =dt .Rows [0]["customeraddress"].ToString ();
    //txt_customeraddress.Text = dt.Rows[0][0].ToString();
    txt_invoiceno.Text = dt.Rows[0][1].ToString();
    txt_orderno.Text = dt.Rows[0][2].ToString();
    txt_ondate.Text = dt.Rows[0][3].ToString();
    cmb_particulars.Text = dt.Rows[0][4].ToString();
    txt_quantity.Text = dt.Rows[0][5].ToString();
    txt_perprice.Text = dt.Rows[0][6].ToString();
    txt_amount.Text = dt.Rows[0][7].ToString();
    txt_vat.Text = dt.Rows[0][8].ToString();
    txt_totalamount.Text = dt.Rows[0][9].ToString();
    txt_netamount.Text = dt.Rows[0][10].ToString();
    }

    }
    }

    Best,
    Sudheep.

    • sudheep
    • December 1st, 2011

    Hi,

    I was designed a windows application form named as updatecustomerinvoice.in this form my issue is.with the name of companyname combobox is there if i choose any companyname name from combobox(cmb_companyname).it has to display the remaining textboxes.i will display my tables here.
    Tbl_report1 columns:
    Invoiceno,particulars,quantity,perprice,amount,invoicedate,ondate,invoiceid,orderno
    Tbl_report2 columns:
    Compname,compaddress,invoiceno(primarykey),orderno,ondate,invoicedate,amountstatus,netamount,netvat,tamount
    Tbl_customer columns:
    Custid,custname,custaddress,custcity,custstate,custstdcode,custphoneno,custmobileno

    in my form I am having these fields like I mentioned above two tables.my issue is if I select the compname it should display the remaining fields.for loading only companynames I wrote the code is below.
    private void loadcompanies()
    {
    SqlConnection con = new SqlConnection(“data source=mars-104;initial catalog=marsweb;integrated security=true”);
    SqlCommand cmd = new SqlCommand(“select ’0′ as compaddress,’selectone’ as compname union select compaddress,compname from dbo.tbl_report2 “, con);//I am using here customer table.for this reason only it shows customer address itself.can you please correct this for getting all fields.
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    if (con.State == ConnectionState.Closed)
    {
    con.Open();
    }
    da.Fill(dt);
    cmb_companyname.DataSource = dt;
    cmb_companyname.DisplayMember = “compname”;
    cmb_companyname.ValueMember = “compaddress”;
    }
    But it shows the customeraddressonly.for that I wrote the code in selectedindexchangedevent.
    private void cmb_companyname_SelectedIndexChanged(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(“data source=mars-104;initial catalog=marsweb;integrated security=true”);
    SqlCommand cmd = new SqlCommand(“select t2.compaddress,t1.invoiceno,t1.orderno,t1.ondate,t1.particulars,t1.perprice,t1.amount,t2.netvat,t2.tamount,t2.netamount from tbl_report2 t2,tbl_report1 t1 where t1.compname=’hdfcbank’ and t2.compname=’hdfcbank’”, con);
    //SqlCommand cmd = new SqlCommand(“select custaddress from tbl_customer where custname=@custname”, con);
    //cmd.Parameters.AddWithValue(“@custname”,cmb_companyname .Text );
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    txt_customeraddress.Text = cmb_companyname.SelectedValue.ToString();
    //txt_orderno.Text = cmb_companyname.SelectedValue.ToString();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
    txt_customeraddress .Text =dt .Rows [0]["customeraddress"].ToString ();
    //txt_customeraddress.Text = dt.Rows[0][0].ToString();
    txt_invoiceno.Text = dt.Rows[0][1].ToString();
    txt_orderno.Text = dt.Rows[0][2].ToString();
    txt_ondate.Text = dt.Rows[0][3].ToString();
    cmb_particulars.Text = dt.Rows[0][4].ToString();
    txt_quantity.Text = dt.Rows[0][5].ToString();
    txt_perprice.Text = dt.Rows[0][6].ToString();
    txt_amount.Text = dt.Rows[0][7].ToString();
    txt_vat.Text = dt.Rows[0][8].ToString();
    txt_totalamount.Text = dt.Rows[0][9].ToString();
    txt_netamount.Text = dt.Rows[0][10].ToString();
    }

    }
    }

    Best,
    Sudheep.

    • atul gupta
    • December 10th, 2011

    This is one of the most useful piece of code that I have come across on the net in a long long time. It has saved hours and hours of my time. Just wanted to know how to validate data while saving, can we get individual values and validate them eg do not allow negative values or values above a cut-off level etc

    • dhanil
    • December 12th, 2011

    wow

    • satish
    • December 12th, 2011

    Hi rahim ,your multiple update code is ultimate….

    Im doing one application that is Attendance Entry form.

    I wnt to display Admision no with checked box’s and checked means Present,unchecked means Absent.how to do These values are will be directly insert aswell as update
    .
    .
    Plz help me how to Do this.Send Sample code for me.

    • thao
    • December 18th, 2011

    thanks so much,but i can question.
    abount update,insert,delete and save from ,save data mdb.
    thao,thanks you

    • thao
    • December 18th, 2011

    update,insert,delete load in form and load in data mdb

    • nadjib
    • December 30th, 2011

    Salam Mr Rahim.
    Great, you know? you saved lot of time for me, I spent to days nights to figure it out but nothing did the purpose but your quick tutorial.
    Greetings.

    • mansi gupta
    • January 4th, 2012

    its the first time i m working with the datagridview… i m not able to insert the data .. actually its being inserted in the datagridview on the screen but my database mdb file is still empty…
    even if i dont enter the records and fire a select query it is not even reacting to it.. help me soon…….Mr.rahim

    • AQUEELHASHMI
    • January 13th, 2012

    hi sir this is a problem is when i update in GridView than exeption
    please help me

    • tushar
    • January 17th, 2012

    hi sir i wnt 2 show a checked checkbox as presents in database and uncheked as absent wht wil be the code and in which state.

    • Mr_kics
    • January 18th, 2012

    hi raheem,
    Plz let me know in datagridview vb.net;how i can restric negative values :
    i am using this: in datagridview validating event:
    If DataGridView1.CurrentRow.Cells(“Amount”).Value < 0.0 Then

    but it is not a good code..

    • Ankit
    • January 22nd, 2012

    i want to apply query on datagrid view acc to user need..
    for eg: user enter name in textbox and corresponding to dis textbox value related rows are selected and data is fetch in grid view..
    pls help.
    its urgent..

    • aa
    • January 24th, 2012

    hi raheem..

    please guide me for entering daily attendance of the employee in a datagridview & clicking on save button will save directly to attendance database table

    pls help on urgent basis

    • Satish Sharma
    • January 25th, 2012

    Hi Rahim

    I want to Know I have 8 Columns & unlimited Rows in DataGridView ,How to store Id of All Rows & Columns in Data

    • satish
    • January 30th, 2012

    Hi rahime

    I want to insert data To Database from grid view When i am Selected particular entire row.And How to Display TextBox ,RadioButtons controls in GridView

    HelpMe Bhyya

  16. thankssssssssssssssssssssssssssssssssssssssssssss

    i need it realy

    i hope bests for you

    • Amar
    • February 27th, 2012

    How to write code for insert using data gridview in windows forms application?

    • swati
    • March 2nd, 2012

    hello sir,
    i want to now when we give command as
    sqlDataAdapter.Update(dataTable);
    this will require update command text .. so i gave update command text as “update bname=? where id=?”
    and for id i got value as e.currentRowIndex, so its updating only 1 row ..

    how to update all record at once ?

    and is their any way to freeze particular row from updating and deleting ?

  17. hai,
    when i clicked add button ;a message appeared that “object reference not set into an instance of an object” \
    plz reply sir

    • Lakshmi
    • March 9th, 2012

    Hi Rahim,
    I am getting “Dynamic SQL generation is not supported under multiple Base Tables”, the reason of the error is I am Joining multiple tables to get the data in the Data grid. Now how should i write the insert command to insert into one table from the Data grid values.

    I could not figure the Parameters for that Insert commnad Can you please let me know the syntax for the Insert and Update commands when we use multiple tables in the select to show the data in the Datagrid.

    Thanks,
    Lakshmi

    • kratika
    • March 13th, 2012

    hello sir could u pls tell me how we can search a single row data from table into gridview according to the user’s input into a textbox…..

    • deepak chandel
    • March 14th, 2012

    my project is school management plz tell me database and who is the use form

    • deepak chandel
    • March 14th, 2012

    helo frids
    update me hi insert krwana chalata hu datagridview ka data plz tell me query

    • Tripti kumbhat
    • March 15th, 2012

    Hi.
    i m Tripti.
    can we add a column in sqlserver database at run time using datagridview. like if we add a col in data gridview at runtime it must reflect the changes in sql server database’ table.
    is it possible?

    code that i used to add col in datagrid at run time..
    DataGridViewTextBoxColumn clsCol1 = new DataGridViewTextBoxColumn();
    clsCol1.HeaderText = “Column 1″;
    clsCol1.ValueType = typeof(System.String);
    this.dataGridView1.Columns.Add(clsCol1);

    pls send me the code for adding col into database.

    thanks in adv.

    • PradeepNair
    • March 19th, 2012

    HI sir,
    i’m filtering the data’s from the sql table and dislplaying in datagridview , now i want to save the filtered content displayed in the datagridveiw in another new sql table. pl help me how to perform it using c#.net. pl send the code to pradeepnair@gmail.com

    • Supun
    • March 21st, 2012

    hi sir,

    i want to insert grid view data to another table.and delete from current table in Sql Database..here is my code…its always insert row no to table not the column value..please help me..current table is jobmain i want to job main row data to jobcompleted.and delete from jobmain.

    string str1 = dataGridView1.Rows[0].Cells[0].Value.ToString();

    string str2 = dataGridView1.Rows[0].Cells[1].Value.ToString();

    string str3 = dataGridView1.Rows[0].Cells[2].Value.ToString();

    string str4 = dataGridView1.Rows[0].Cells[3].Value.ToString();

    string str5 = dataGridView1.Rows[0].Cells[4].Value.ToString();

    string str6 = dataGridView1.Rows[0].Cells[5].Value.ToString();

    string str7 = dataGridView1.Rows[0].Cells[6].Value.ToString();

    try
    {
    System.Collections.ArrayList alv = new System.Collections.ArrayList();

    String connectionString = @”Data Source=GTL-ATTENDANCE;Initial Catalog=C:\USERS\NIROSH\DESKTOP\JOB ALLOCATION\JOB ALLOCATION\APP_DATA\JOB.MDF;User ID=sa;Password=orchard”;
    SqlConnection conn2 = new SqlConnection(connectionString);
    conn2.Open();

    SqlCommand cm = new SqlCommand();

    string qry = “SELECT * FROM JobCompleted”;

    SqlDataAdapter adapter = new SqlDataAdapter(qry, conn2);
    DataTable dt = new DataTable();
    adapter.Fill(dt);

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {

    cm.CommandText = "INSERT into JobCompleted(jobID,jobDescription,jobPerson,jobOpenDate,jobCloseDate,Remarks,CurrentNo) values (" + str1 + "," + str2 + "," + str3 + "," + str4 + "," + str5 + "," + str6 + "," + str7 + ")";

    cm.Connection = conn2;
    int count = cm.ExecuteNonQuery();
    conn2.Close();

    MessageBox.Show("updated");

    }

    }
    catch (Exception d)
    {
    MessageBox.Show(d.ToString());

    }

    • Narayan Nyaupane
    • March 22nd, 2012

    Many many thank you rahim ji,

    aapka code bade aachhe hai.

    thank u a lot for your very very important code.

  18. hi my dear
    your blog is fun and nice
    thanks
    have good times
    ————————–
    i’m majid ahmadi from tehran-iran
    network eng

    • Anshu
    • March 24th, 2012

    hello sir…….
    i used your whole code…..but still i found run time error on updating and deleting……..
    error is
    “object refrence not set to an instance of object”
    plz……tell me……the reason of this error……
    plz reply me soon……
    Thanx…..!!!!

      • Tripti kumbhat
      • March 25th, 2012

      Hi Anshu,
      before using above code make ensure that
      1) one primary must be exist in ur data base.
      2) to modify data in dataset
      without the sql command builder this line would be fail
      da.Update(dt);

      still if u r getting problem , then leave a comment here.

    • shoaib attari
    • April 3rd, 2012

    salam rahem
    i write your code in my project but i have a single error in this line
    connectionString = ConfigurationManager.AppSettings["connectionString"];
    underlined “ConfigurationManager” this word please tell me its solution?
    thanks

      • XTG
      • April 8th, 2013

      Gajanan :
      I want code in 3 tire Architecture ….plz send me code

      are u sure u have added System.Configuration to your references and
      included it in your code like;

      using System.Configuration;

    • hitesh
    • April 9th, 2012

    Hello sir….
    i used your code in my application for insert,delete and update from datagridview to sql but it giving an error
    “The name ‘ConfigurationManager’ does not exist in the current context”
    so please give a solution

  19. hello….Rahim bro…..
    i learning software fresh…..

    i using name space bellow for the data girdview..

    using System.Data.SqlClient;
    using System.Data;
    using System.Configuration;

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["regi1 con"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {

    i write code in this function but dont supported
    wat i can do jus plz rply me
    my email id:

    zakiryungster@gmail.com

    all solution reply me this email…

    god bless you bro…

    }

  20. Hello
    Please help me. I just want to add new row, but do not update the old records.

    Method below it’s update all records, maybe slow down the system?

    private void addUpadateButton_Click(object sender, EventArgs e)
    {
    try
    {
    sqlDataAdapter.Update(dataTable);
    }
    catch (Exception exceptionObj)
    {
    MessageBox.Show(exceptionObj.Message.ToString());
    }
    }
    other way to add the rows faster ???

      • Tripti kumbhat
      • April 26th, 2012

      Hi,
      in ur case u should use Insert query instead of this statment…

      • how to insert at datagridview? i only can insert from textbox

        • Tripti kumbhat
        • May 1st, 2012

        datagridview1.Rows[0].Cells[0].Value.ToString();

    • Justin W.
    • May 2nd, 2012

    This post was exactly what I was looking for! Thank you for the amazing tutorial!

    • saurabh
    • May 15th, 2012

    it’s working nice
    thank you very much

    • Honey
    • May 25th, 2012

    Hi Rahim,
    I used your code for update but the changes done are not reflecting in database. Can you please assist in this ?

    • Honey
    • May 25th, 2012

    Hey, i got it. Thanks so much.

    • Sumbul
    • June 16th, 2012

    Excellent blog :)
    m sick of searching for this solution…
    hatts off to u :)

    • Geeta
    • July 4th, 2012

    I wrote above code but its giving exception for connection string

    On this below line
    sqlConnection.Open();

    (The Connection String property has not been initialized.)

    Please help me to solve this …
    TX :)

    • helina
    • July 11th, 2012

    hey can you tell me all steps to write a code using a button to insert a data into a database in c# 2010 visual studio

    • CHAITANYA KIRAN KASANI
    • July 27th, 2012

    When i click on Add\update button, a dialog box showing syntax error INSERT INTO and when i click on Delete button it also shows a dialog “Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information”
    why it is happening like please give me reply….

      • Durga Muthu
      • August 30th, 2012

      ya im also getting the same error as mentioned above, we cannot use this code if we dont have primary key in our table, so pls help us to go for non primary key table also, waiting for ur reply

      • I am not actually sure how to do this with tables without primary key, will have a look at this, will let you know if I can get this done..

    • rehan khan
    • September 19th, 2012

    hi rahim sir .. please i need code of update and delete from gridview but as u given above code that is not understanding to me.. i had dowloaded your above source also.. but how to restore mdf and ldf files in sql server

    • manasi
    • January 12th, 2013

    your code is not working..

  21. thnk’s…

    • Nandita panda
    • March 26th, 2013

    How i insert modify and delete “DATA GRIDVIEW”data?

    • Yakubmiya Mohammed
    • May 5th, 2013

    HI rahim

    i am having doubt regarding sqldataAdapter.Update(datatable)
    Actually am using Oracle for the same thing i wrote like follwoing
    OledbDataAdapter.Update(DataTable);

    it has gave an error
    please help me on this.

    Thanks,
    Mohammed Yakub

    • ĐOÀN VĂN THỌ
    • May 7th, 2013

    GOOD. THANHK

  22. Hi!

    DataGridView control are used very frequently in C#. It has various type of functionality but comman funcatin are CRUD operation. So thanks for sharing your

    kanowledge. There are few other links that have described CRUD (Insert, Delete, Update) operation with good explaination and proper sample. I hope that’s helpful for

    beginners.

    http://www.mindstick.com/Articles/9422cfc8-c2ed-4ec1-9fab-589eb850a863/?Insert%20Delete%20Update%20in%20DataGridView%20with%20DataTable%20in%20C

    http://www.dreamincode.net/forums/topic/238727-insert-update-and-delete-records-in-table-with-datagridview-using-c%23/

    • ravikumar
    • July 22nd, 2013
  23. Great post.

    • Sulman
    • September 15th, 2013

    Sir can you post the complete code of storing image into sql server and retrieve image from sql server to picture box

    • Jirapan
    • September 15th, 2013

    Thank you very much.

  24. Thank you for the great share…been a while since i do programming. But i have a new project now that requires i’ll be hands on again.

    • toby
    • October 14th, 2013
    • saeed shoja
    • October 21st, 2013

    special thanks to rahimkhan
    your post was very helpful to me

    • Priyanka K
    • November 17th, 2013

    Thank You So Much…!!!

  25. Hi there, all is going sound here and ofcourse every one is sharing facts, that’s truly excellent, keep up writing.

  1. January 3rd, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 74 other followers

%d bloggers like this: