Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Inserting row in DataGridView doesn't update Primary Key

Inserting row in DataGridView doesn't update Primary Key

Scheduled Pinned Locked Moved C#
csharpdatabasehelpcssdotnet
6 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    dj_jeff
    wrote on last edited by
    #1

    I'm only using Visual C# 2008 Express Edition for a .NET Framework 2.0 project. So, I'm not able to use an assistent creating a connection to a MS SQL 2005 database on another server, it has to be done in code. The table itself has a field which is automatically a primary key with autoincrement functionality. Selecting all fields in the table are no problem with SqlConnection-, SqlDataAdapter etc. I'm also able to update an existing entry. My problem is inserting a new row. The new set is added to the table, but I'm not automatically getting back the new Primary Key value in the ID field (it's also not in the DataTable during debugging) :mad:. Next time, I'm editing this field, I'm getting an error, of course for updating it needs the new ID, the DataGridView-/ DataTable- Object doesn't know. Probably it's very easy, but how can this ID can be updated in the DataGridView and let the dataset navigator of the grid stay at the current position (no reload with moving the navigator to the first set).

    L 1 Reply Last reply
    0
    • D dj_jeff

      I'm only using Visual C# 2008 Express Edition for a .NET Framework 2.0 project. So, I'm not able to use an assistent creating a connection to a MS SQL 2005 database on another server, it has to be done in code. The table itself has a field which is automatically a primary key with autoincrement functionality. Selecting all fields in the table are no problem with SqlConnection-, SqlDataAdapter etc. I'm also able to update an existing entry. My problem is inserting a new row. The new set is added to the table, but I'm not automatically getting back the new Primary Key value in the ID field (it's also not in the DataTable during debugging) :mad:. Next time, I'm editing this field, I'm getting an error, of course for updating it needs the new ID, the DataGridView-/ DataTable- Object doesn't know. Probably it's very easy, but how can this ID can be updated in the DataGridView and let the dataset navigator of the grid stay at the current position (no reload with moving the navigator to the first set).

      L Offline
      L Offline
      led mike
      wrote on last edited by
      #2

      dj_jeff wrote:

      connection to a MS SQL 2005

      dj_jeff wrote:

      The table itself has a field which is automatically a primary key with autoincrement functionality.

      Microsoft cleverly hides that information in the documentation[^]

      led mike

      D 1 Reply Last reply
      0
      • L led mike

        dj_jeff wrote:

        connection to a MS SQL 2005

        dj_jeff wrote:

        The table itself has a field which is automatically a primary key with autoincrement functionality.

        Microsoft cleverly hides that information in the documentation[^]

        led mike

        D Offline
        D Offline
        dj_jeff
        wrote on last edited by
        #3

        led mike wrote:

        Microsoft cleverly hides that information in the documentation[^]

        I don't really know where I should handle this. Everything is controlled by the BindingNavigator and BindingSource. The document samples refer to a manual insert and console display. Here's my current code of that Test form. I guess Insert handling in RowsAdded- Event wouldn't be good because of running this event on building the datagridview.

        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 DummyProject
        {
        public partial class frmTest : Form
        {
        SqlDataAdapter dataAdapter;
        DataTable table;
        SqlCommandBuilder commandBuilder;

        	public frmTest()
        	{
        		InitializeComponent();
        	}
        
        	private void updateGridView()
        	{
        		this.Validate();
        		tblLangBindingSource.EndEdit();
        		dataAdapter.Update(table);
        	}
        	
        	private void frmTest\_Load(object sender, EventArgs e)
        	{
        		string strCon = "Data Source=MyServer;Initial Catalog=MyDB;User ID=MyUser;Password=MyPass;";
        		string strSQL = "select LangId AS ID, LangName AS Name FROM tbl\_Lang";
        		dataAdapter = new SqlDataAdapter(strSQL, strCon);
        		commandBuilder = new SqlCommandBuilder(dataAdapter);
        
        		// Populate a new data table and bind it to the BindingSource.
        		table = new DataTable();
        		table.Locale = System.Globalization.CultureInfo.InvariantCulture;
        		dataAdapter.Fill(table);
        		tblLangBindingSource.DataSource = table;
        
        		// Resize the DataGridView columns to fit the newly loaded content.
        		dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        
        		// you can make it grid readonly.
        		//dataGridView1.ReadOnly = true;  
        
        		// finally bind the data to the grid
        		dataGridView1.DataSource = tblLangBindingSource;
        		bindingNavigator1.BindingSource = tblLangBindingSource;
        	}
        
        	private void dataGridView1\_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        	{
        		this.updateGridView();
        	}
        
        	private void dataGridView1\_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        	{
        		this.updateGridView();
        	}
        
        	private void dataGridView1\_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        	{
        		this.updateGridView();
        	}
        
        	private void bindingNavigatorDeleteItem\_Click(object sender, EventArgs e)
        	{
        		foreach(DataGridViewRow dgvr in d
        
        L 1 Reply Last reply
        0
        • D dj_jeff

          led mike wrote:

          Microsoft cleverly hides that information in the documentation[^]

          I don't really know where I should handle this. Everything is controlled by the BindingNavigator and BindingSource. The document samples refer to a manual insert and console display. Here's my current code of that Test form. I guess Insert handling in RowsAdded- Event wouldn't be good because of running this event on building the datagridview.

          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 DummyProject
          {
          public partial class frmTest : Form
          {
          SqlDataAdapter dataAdapter;
          DataTable table;
          SqlCommandBuilder commandBuilder;

          	public frmTest()
          	{
          		InitializeComponent();
          	}
          
          	private void updateGridView()
          	{
          		this.Validate();
          		tblLangBindingSource.EndEdit();
          		dataAdapter.Update(table);
          	}
          	
          	private void frmTest\_Load(object sender, EventArgs e)
          	{
          		string strCon = "Data Source=MyServer;Initial Catalog=MyDB;User ID=MyUser;Password=MyPass;";
          		string strSQL = "select LangId AS ID, LangName AS Name FROM tbl\_Lang";
          		dataAdapter = new SqlDataAdapter(strSQL, strCon);
          		commandBuilder = new SqlCommandBuilder(dataAdapter);
          
          		// Populate a new data table and bind it to the BindingSource.
          		table = new DataTable();
          		table.Locale = System.Globalization.CultureInfo.InvariantCulture;
          		dataAdapter.Fill(table);
          		tblLangBindingSource.DataSource = table;
          
          		// Resize the DataGridView columns to fit the newly loaded content.
          		dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
          
          		// you can make it grid readonly.
          		//dataGridView1.ReadOnly = true;  
          
          		// finally bind the data to the grid
          		dataGridView1.DataSource = tblLangBindingSource;
          		bindingNavigator1.BindingSource = tblLangBindingSource;
          	}
          
          	private void dataGridView1\_CellEndEdit(object sender, DataGridViewCellEventArgs e)
          	{
          		this.updateGridView();
          	}
          
          	private void dataGridView1\_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
          	{
          		this.updateGridView();
          	}
          
          	private void dataGridView1\_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
          	{
          		this.updateGridView();
          	}
          
          	private void bindingNavigatorDeleteItem\_Click(object sender, EventArgs e)
          	{
          		foreach(DataGridViewRow dgvr in d
          
          L Offline
          L Offline
          led mike
          wrote on last edited by
          #4

          dj_jeff wrote:

          The document samples refer to a manual insert and console display.

          The answers you seek are in the article, this of course requires you to read the article.

          led mike

          D 1 Reply Last reply
          0
          • L led mike

            dj_jeff wrote:

            The document samples refer to a manual insert and console display.

            The answers you seek are in the article, this of course requires you to read the article.

            led mike

            D Offline
            D Offline
            dj_jeff
            wrote on last edited by
            #5

            Seems to work with the InsertCommand attributes on UserAddedRow event. I'm getting back an autoincrement value in my grid and it seems to be stored always on the SQL table. :) Why has this to be so complicated ? Microsoft's always dealing with it's features but can't make this handling easier.

            L 1 Reply Last reply
            0
            • D dj_jeff

              Seems to work with the InsertCommand attributes on UserAddedRow event. I'm getting back an autoincrement value in my grid and it seems to be stored always on the SQL table. :) Why has this to be so complicated ? Microsoft's always dealing with it's features but can't make this handling easier.

              L Offline
              L Offline
              led mike
              wrote on last edited by
              #6

              dj_jeff wrote:

              but can't make this handling easier.

              If you are looking for easy work, I suggest you choose a different career. The generally accept view, by uneducated people of software development, that it's easy and anyone can do it, is complete hogwash. It has always been complicated and there are no signs that will change in near future. You might want to watch the video accessible from this web page.[^]

              led mike

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups