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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Update in C# using SQL Server Database.

Update in C# using SQL Server Database.

Scheduled Pinned Locked Moved C#
csharpdatabasehelpsharepointsql-server
50 Posts 4 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.
  • N Offline
    N Offline
    Norris Chappell
    wrote on last edited by
    #1

    I have a datagridview that I changed the name Jones to Brown in a row. Now I need to update my SqlServer table with that change. I am using C# for the code and SqlServer 2010 for the database and SharePoint to display the data as a webpart. I have read almost everything on the internet and can't seem to find an answer to my issue. Datagridview KeyPer Test Name Doe Smith Jones I change a name in the Name column KeyPer Test Name Doe Smith brown I'm having trouble getting past this setting of the parameter for ID. It is giving me am error: The name ID does not exist in the current content. Code Behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;

    namespace StaffingWebParts.KeyPerTest
    {
    public partial class KeyPerTestUserControl : UserControl
    {
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString);
    SqlCommand cmd = new SqlCommand();
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    DataTable dt = new DataTable();

                dt.Columns.Add("Name");
                dt.Columns.Add("VDCIDIQ");
                dt.Columns.Add("VDCFFS");
                dt.Columns.Add("VDCHIM");
                dt.Columns.Add("VDCWEBHOSTING");
                dt.Columns.Add("VDCCWF");
                SqlDataReader myReader = null;
                SqlCommand cmd = new SqlCommand("SELECT distinct  Name, VDCIDIQ , VDCFFS, VDCHIM, VDCWEBHOSTING, VDCCWF  from CMS\_Key\_Personnel where Name <> '   ' order by  Name");
                cmd.Connection = conn;
                conn.Open();
                myReader = cmd.ExecuteReader();
                while (myReader.Read())
                {
                    DataRow dr = dt.NewRow();
                    dr\[0\] = myReader\["Name"\].ToString();
                    dr\[1\] = myReader\["VDCIDIQ"\].ToString();
                    dr\[2\] = myReader\["VDCFFS"\].ToString();
                    dr\[3\] = myReader\["VDCHIM"\].ToString();
                    dr\[4\] = myReader\["VDCWEBHOSTING"\].ToString();
                    dr\[5\] = myReader\["VDCCWF"\].ToString();
    
    A 1 Reply Last reply
    0
    • N Norris Chappell

      I have a datagridview that I changed the name Jones to Brown in a row. Now I need to update my SqlServer table with that change. I am using C# for the code and SqlServer 2010 for the database and SharePoint to display the data as a webpart. I have read almost everything on the internet and can't seem to find an answer to my issue. Datagridview KeyPer Test Name Doe Smith Jones I change a name in the Name column KeyPer Test Name Doe Smith brown I'm having trouble getting past this setting of the parameter for ID. It is giving me am error: The name ID does not exist in the current content. Code Behind

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.Data.Sql;
      using System.Data.SqlClient;
      using System.Configuration;
      using System.Data;

      namespace StaffingWebParts.KeyPerTest
      {
      public partial class KeyPerTestUserControl : UserControl
      {
      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString);
      SqlCommand cmd = new SqlCommand();
      protected void Page_Load(object sender, EventArgs e)
      {
      if (!Page.IsPostBack)
      {
      DataTable dt = new DataTable();

                  dt.Columns.Add("Name");
                  dt.Columns.Add("VDCIDIQ");
                  dt.Columns.Add("VDCFFS");
                  dt.Columns.Add("VDCHIM");
                  dt.Columns.Add("VDCWEBHOSTING");
                  dt.Columns.Add("VDCCWF");
                  SqlDataReader myReader = null;
                  SqlCommand cmd = new SqlCommand("SELECT distinct  Name, VDCIDIQ , VDCFFS, VDCHIM, VDCWEBHOSTING, VDCCWF  from CMS\_Key\_Personnel where Name <> '   ' order by  Name");
                  cmd.Connection = conn;
                  conn.Open();
                  myReader = cmd.ExecuteReader();
                  while (myReader.Read())
                  {
                      DataRow dr = dt.NewRow();
                      dr\[0\] = myReader\["Name"\].ToString();
                      dr\[1\] = myReader\["VDCIDIQ"\].ToString();
                      dr\[2\] = myReader\["VDCFFS"\].ToString();
                      dr\[3\] = myReader\["VDCHIM"\].ToString();
                      dr\[4\] = myReader\["VDCWEBHOSTING"\].ToString();
                      dr\[5\] = myReader\["VDCCWF"\].ToString();
      
      A Offline
      A Offline
      Agent__007
      wrote on last edited by
      #2

      Look at this line:

      cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;

      What is "id" (on the RHS of that assignment statement) here? I think that should be it. -- EDIT I don't see any "ID" column you are fetching while binding the data to the grid. So, I am not sure from where you will be using that in your SQL statement. Perhaps a label or something else somewhere on the page? :~

      You have just been Sharapova'd.

      N 2 Replies Last reply
      0
      • A Agent__007

        Look at this line:

        cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;

        What is "id" (on the RHS of that assignment statement) here? I think that should be it. -- EDIT I don't see any "ID" column you are fetching while binding the data to the grid. So, I am not sure from where you will be using that in your SQL statement. Perhaps a label or something else somewhere on the page? :~

        You have just been Sharapova'd.

        N Offline
        N Offline
        Norris Chappell
        wrote on last edited by
        #3

        The id is the [ID] [int] IDENTITY(1,1) NOT NULL, field. Do I need to show it on my datgridview?

        1 Reply Last reply
        0
        • A Agent__007

          Look at this line:

          cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;

          What is "id" (on the RHS of that assignment statement) here? I think that should be it. -- EDIT I don't see any "ID" column you are fetching while binding the data to the grid. So, I am not sure from where you will be using that in your SQL statement. Perhaps a label or something else somewhere on the page? :~

          You have just been Sharapova'd.

          N Offline
          N Offline
          Norris Chappell
          wrote on last edited by
          #4

          When I use this code cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; I am getting this error: The name 'id' does not exist in the current context

          A 1 Reply Last reply
          0
          • N Norris Chappell

            When I use this code cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; I am getting this error: The name 'id' does not exist in the current context

            A Offline
            A Offline
            Agent__007
            wrote on last edited by
            #5

            Norris Chappell wrote:

            I am getting this error: The name 'id' does not exist in the current context

            Yes, that's what I was referring to. You don't have a variable "id" from which you are assigning your "@ID" parameter a value. Even though your "ID" is an identity column, you will still need its value in order to execute your UPDATE query. How else will you be uniquely identifying the row which you need to be updated? :) Here's what you can do (top off my head, as I worked on ASP.NET WebForms a long time ago :) ): 0. Select and bind your ID column to your grid but make it invisible. 1. Use DataKeys[^] property of grid for setting the "ID" field. 2. While updating a row, retrieve the "ID" value for it using its DataKeys property (and possibly its index). 3. Use this value to pass in to your update query, i.e. the value for your "@ID" parameter.

            You have just been Sharapova'd.

            N 1 Reply Last reply
            0
            • A Agent__007

              Norris Chappell wrote:

              I am getting this error: The name 'id' does not exist in the current context

              Yes, that's what I was referring to. You don't have a variable "id" from which you are assigning your "@ID" parameter a value. Even though your "ID" is an identity column, you will still need its value in order to execute your UPDATE query. How else will you be uniquely identifying the row which you need to be updated? :) Here's what you can do (top off my head, as I worked on ASP.NET WebForms a long time ago :) ): 0. Select and bind your ID column to your grid but make it invisible. 1. Use DataKeys[^] property of grid for setting the "ID" field. 2. While updating a row, retrieve the "ID" value for it using its DataKeys property (and possibly its index). 3. Use this value to pass in to your update query, i.e. the value for your "@ID" parameter.

              You have just been Sharapova'd.

              N Offline
              N Offline
              Norris Chappell
              wrote on last edited by
              #6

              I was able to do #1. #2 - Now to get the DataKeys what is the Code behind to do that?

              N 1 Reply Last reply
              0
              • N Norris Chappell

                I was able to do #1. #2 - Now to get the DataKeys what is the Code behind to do that?

                N Offline
                N Offline
                Norris Chappell
                wrote on last edited by
                #7

                Hi, I'm getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Here is my code?

                protected void Button_Update(object sender, EventArgs e)

                        {
                          using(SqlCommand cmd = new SqlCommand())
                         {
                
                             foreach (GridViewRow row in gvKeyPersonnel.Rows)
                             {
                                
                                 cmd.Connection = conn;
                                 conn.Open();
                                 cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name  WHERE ID = @id";
                
                                     cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                 cmd.Parameters.AddWithValue("@Name", Convert.ToString(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[1\]));       
                
                                 int numRegs = cmd.ExecuteNonQuery();
                             }
                               conn.Close();
                         }
                         }
                

                Update the two Parameters but still gets the OOR error.

                M A 2 Replies Last reply
                0
                • N Norris Chappell

                  Hi, I'm getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Here is my code?

                  protected void Button_Update(object sender, EventArgs e)

                          {
                            using(SqlCommand cmd = new SqlCommand())
                           {
                  
                               foreach (GridViewRow row in gvKeyPersonnel.Rows)
                               {
                                  
                                   cmd.Connection = conn;
                                   conn.Open();
                                   cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name  WHERE ID = @id";
                  
                                       cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                   cmd.Parameters.AddWithValue("@Name", Convert.ToString(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[1\]));       
                  
                                   int numRegs = cmd.ExecuteNonQuery();
                               }
                                 conn.Close();
                           }
                           }
                  

                  Update the two Parameters but still gets the OOR error.

                  M Offline
                  M Offline
                  Mycroft Holmes
                  wrote on last edited by
                  #8

                  Your issue is probably on cmd.ExecuteNonQuery not returning anything from the query remove the int numregs = and see what you get

                  Never underestimate the power of human stupidity RAH

                  N 1 Reply Last reply
                  0
                  • M Mycroft Holmes

                    Your issue is probably on cmd.ExecuteNonQuery not returning anything from the query remove the int numregs = and see what you get

                    Never underestimate the power of human stupidity RAH

                    N Offline
                    N Offline
                    Norris Chappell
                    wrote on last edited by
                    #9

                    Mycroft, I am now getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index. I think something is wrong with this parameter? cmd.Parameters.AddWithValue("@Name", Convert.ToChar(gvKeyPersonnel.DataKeys[row.RowIndex].Values[0])); I don't know if I should have two Datakeys?

                    M 1 Reply Last reply
                    0
                    • N Norris Chappell

                      Mycroft, I am now getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index. I think something is wrong with this parameter? cmd.Parameters.AddWithValue("@Name", Convert.ToChar(gvKeyPersonnel.DataKeys[row.RowIndex].Values[0])); I don't know if I should have two Datakeys?

                      M Offline
                      M Offline
                      Mycroft Holmes
                      wrote on last edited by
                      #10

                      What I would do is create 2 variables to hold the cell values, put a break point in the loop and check the values before they are passed to the parameters.

                      Never underestimate the power of human stupidity RAH

                      1 Reply Last reply
                      0
                      • N Norris Chappell

                        Hi, I'm getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Here is my code?

                        protected void Button_Update(object sender, EventArgs e)

                                {
                                  using(SqlCommand cmd = new SqlCommand())
                                 {
                        
                                     foreach (GridViewRow row in gvKeyPersonnel.Rows)
                                     {
                                        
                                         cmd.Connection = conn;
                                         conn.Open();
                                         cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name  WHERE ID = @id";
                        
                                             cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                         cmd.Parameters.AddWithValue("@Name", Convert.ToString(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[1\]));       
                        
                                         int numRegs = cmd.ExecuteNonQuery();
                                     }
                                       conn.Close();
                                 }
                                 }
                        

                        Update the two Parameters but still gets the OOR error.

                        A Offline
                        A Offline
                        Agent__007
                        wrote on last edited by
                        #11

                        Norris Chappell wrote:

                        cmd.Parameters.AddWithValue("@Name", Convert.ToString(gvKeyPersonnel.DataKeys[row.RowIndex].Values[1]));

                        This statement shouldn't be there, you should only have your "ID" field in the DataKeys. Instead, you should be having something like this:

                        cmd.Parameters.AddWithValue("@Name", row.Cells[IndexOfCellContainingNameField].Text); // Note that, I am assuming you are not having any template for your "Name" field, like a label, in which case you need to use FindControl() method on your cell and then use .Text on that label

                        Regarding the IndexOutOfRangeException you are getting, I think if you only have the "ID" in the DataKeys property (i.e. remove the "Name" from DataKeys and pass its value like the above line), that won't come up - assuming your RowIndex is not the culprit. Not related to your current question, but I think if you are having to iterate all rows in the grid for updating a row, you might want to have a look at examples here[^], here[^] or here[^].

                        You have just been Sharapova'd.

                        N 1 Reply Last reply
                        0
                        • A Agent__007

                          Norris Chappell wrote:

                          cmd.Parameters.AddWithValue("@Name", Convert.ToString(gvKeyPersonnel.DataKeys[row.RowIndex].Values[1]));

                          This statement shouldn't be there, you should only have your "ID" field in the DataKeys. Instead, you should be having something like this:

                          cmd.Parameters.AddWithValue("@Name", row.Cells[IndexOfCellContainingNameField].Text); // Note that, I am assuming you are not having any template for your "Name" field, like a label, in which case you need to use FindControl() method on your cell and then use .Text on that label

                          Regarding the IndexOutOfRangeException you are getting, I think if you only have the "ID" in the DataKeys property (i.e. remove the "Name" from DataKeys and pass its value like the above line), that won't come up - assuming your RowIndex is not the culprit. Not related to your current question, but I think if you are having to iterate all rows in the grid for updating a row, you might want to have a look at examples here[^], here[^] or here[^].

                          You have just been Sharapova'd.

                          N Offline
                          N Offline
                          Norris Chappell
                          wrote on last edited by
                          #12

                          Hi, I don't have any of my fields with a label. I'm still getting an Out of Range error.

                          protected void Button_Update(object sender, EventArgs e)
                          {
                          using (SqlCommand cmd = new SqlCommand())
                          {

                                      // SqlDataReader myReader = null;
                                      // myReader = cmd.ExecuteReader();
                                      foreach (GridViewRow row in gvKeyPersonnel.Rows)
                                      {
                          
                                          cmd.Connection = conn;
                                          conn.Open();
                          
                                          cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name, VDCIDIQ = @VDCIDIQ, VDCFFS = @VDCFFS, VDCHIM = @VDCHIM, VDCWEBHOSTING = @VDCWEBHOSTING, VDCCWF = @VDCCWF WHERE ID = @id";
                          
                                          cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                          cmd.Parameters.AddWithValue("@Name", row.Cells\[1\].Text);
                                          cmd.Parameters.AddWithValue("@VDCIDIQ", row.Cells\[2\].Text);
                                          cmd.Parameters.AddWithValue("@VDCFFS", row.Cells\[3\].Text);
                                          cmd.Parameters.AddWithValue("@VDCHIM", row.Cells\[4\].Text);
                                          cmd.Parameters.AddWithValue("@VDCWEBHOSTING", row.Cells\[5\].Text);
                                          cmd.Parameters.AddWithValue("@VDCCWF", row.Cells\[6\].Text);
                                          cmd.ExecuteNonQuery();
                                      }
                                      conn.Close();
                                  }
                              }
                          
                          A M P 3 Replies Last reply
                          0
                          • N Norris Chappell

                            Hi, I don't have any of my fields with a label. I'm still getting an Out of Range error.

                            protected void Button_Update(object sender, EventArgs e)
                            {
                            using (SqlCommand cmd = new SqlCommand())
                            {

                                        // SqlDataReader myReader = null;
                                        // myReader = cmd.ExecuteReader();
                                        foreach (GridViewRow row in gvKeyPersonnel.Rows)
                                        {
                            
                                            cmd.Connection = conn;
                                            conn.Open();
                            
                                            cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name, VDCIDIQ = @VDCIDIQ, VDCFFS = @VDCFFS, VDCHIM = @VDCHIM, VDCWEBHOSTING = @VDCWEBHOSTING, VDCCWF = @VDCCWF WHERE ID = @id";
                            
                                            cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                            cmd.Parameters.AddWithValue("@Name", row.Cells\[1\].Text);
                                            cmd.Parameters.AddWithValue("@VDCIDIQ", row.Cells\[2\].Text);
                                            cmd.Parameters.AddWithValue("@VDCFFS", row.Cells\[3\].Text);
                                            cmd.Parameters.AddWithValue("@VDCHIM", row.Cells\[4\].Text);
                                            cmd.Parameters.AddWithValue("@VDCWEBHOSTING", row.Cells\[5\].Text);
                                            cmd.Parameters.AddWithValue("@VDCCWF", row.Cells\[6\].Text);
                                            cmd.ExecuteNonQuery();
                                        }
                                        conn.Close();
                                    }
                                }
                            
                            A Offline
                            A Offline
                            Agent__007
                            wrote on last edited by
                            #13

                            Just a quick suggestion - try your row.Cells[1].Text, row.Cells[2].Text, ... statements with [0], [1], and so on - i.e. with a Zero-based index. I think that should be it. If not, without a debugger, I can't help you any further, I am afraid.

                            You have just been Sharapova'd.

                            1 Reply Last reply
                            0
                            • N Norris Chappell

                              Hi, I don't have any of my fields with a label. I'm still getting an Out of Range error.

                              protected void Button_Update(object sender, EventArgs e)
                              {
                              using (SqlCommand cmd = new SqlCommand())
                              {

                                          // SqlDataReader myReader = null;
                                          // myReader = cmd.ExecuteReader();
                                          foreach (GridViewRow row in gvKeyPersonnel.Rows)
                                          {
                              
                                              cmd.Connection = conn;
                                              conn.Open();
                              
                                              cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name, VDCIDIQ = @VDCIDIQ, VDCFFS = @VDCFFS, VDCHIM = @VDCHIM, VDCWEBHOSTING = @VDCWEBHOSTING, VDCCWF = @VDCCWF WHERE ID = @id";
                              
                                              cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                              cmd.Parameters.AddWithValue("@Name", row.Cells\[1\].Text);
                                              cmd.Parameters.AddWithValue("@VDCIDIQ", row.Cells\[2\].Text);
                                              cmd.Parameters.AddWithValue("@VDCFFS", row.Cells\[3\].Text);
                                              cmd.Parameters.AddWithValue("@VDCHIM", row.Cells\[4\].Text);
                                              cmd.Parameters.AddWithValue("@VDCWEBHOSTING", row.Cells\[5\].Text);
                                              cmd.Parameters.AddWithValue("@VDCCWF", row.Cells\[6\].Text);
                                              cmd.ExecuteNonQuery();
                                          }
                                          conn.Close();
                                      }
                                  }
                              
                              M Offline
                              M Offline
                              Mycroft Holmes
                              wrote on last edited by
                              #14

                              Caveat, can the user reorder your DGV columns, this would change the index of the cells and screw up your code.

                              Never underestimate the power of human stupidity RAH

                              1 Reply Last reply
                              0
                              • N Norris Chappell

                                Hi, I don't have any of my fields with a label. I'm still getting an Out of Range error.

                                protected void Button_Update(object sender, EventArgs e)
                                {
                                using (SqlCommand cmd = new SqlCommand())
                                {

                                            // SqlDataReader myReader = null;
                                            // myReader = cmd.ExecuteReader();
                                            foreach (GridViewRow row in gvKeyPersonnel.Rows)
                                            {
                                
                                                cmd.Connection = conn;
                                                conn.Open();
                                
                                                cmd.CommandText = "UPDATE SP2010\_EDCStaffing\_AppDB.dbo.CMS\_Key\_Personnel  SET  Name = @Name, VDCIDIQ = @VDCIDIQ, VDCFFS = @VDCFFS, VDCHIM = @VDCHIM, VDCWEBHOSTING = @VDCWEBHOSTING, VDCCWF = @VDCCWF WHERE ID = @id";
                                
                                                cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys\[row.RowIndex\].Values\[0\]));
                                                cmd.Parameters.AddWithValue("@Name", row.Cells\[1\].Text);
                                                cmd.Parameters.AddWithValue("@VDCIDIQ", row.Cells\[2\].Text);
                                                cmd.Parameters.AddWithValue("@VDCFFS", row.Cells\[3\].Text);
                                                cmd.Parameters.AddWithValue("@VDCHIM", row.Cells\[4\].Text);
                                                cmd.Parameters.AddWithValue("@VDCWEBHOSTING", row.Cells\[5\].Text);
                                                cmd.Parameters.AddWithValue("@VDCCWF", row.Cells\[6\].Text);
                                                cmd.ExecuteNonQuery();
                                            }
                                            conn.Close();
                                        }
                                    }
                                
                                P Offline
                                P Offline
                                Pete OHanlon
                                wrote on last edited by
                                #15

                                If you put a breakpoint on cmd.CommandText, press F5 and step through the code when the debugger hits this line. Look to see which one of those lines the application crashes on. As a hint, you can use Visual Studio to inspect the values of each cell to see what's in it.

                                N 1 Reply Last reply
                                0
                                • P Pete OHanlon

                                  If you put a breakpoint on cmd.CommandText, press F5 and step through the code when the debugger hits this line. Look to see which one of those lines the application crashes on. As a hint, you can use Visual Studio to inspect the values of each cell to see what's in it.

                                  N Offline
                                  N Offline
                                  Norris Chappell
                                  wrote on last edited by
                                  #16

                                  Hi Pete, It crashes on this line: cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys[row.RowIndex].Values[0])); The value is null.

                                  P 1 Reply Last reply
                                  0
                                  • N Norris Chappell

                                    Hi Pete, It crashes on this line: cmd.Parameters.AddWithValue("@id", Convert.ToInt32(gvKeyPersonnel.DataKeys[row.RowIndex].Values[0])); The value is null.

                                    P Offline
                                    P Offline
                                    Pete OHanlon
                                    wrote on last edited by
                                    #17

                                    Now that you know the line, you need to identify which part is the problem. Is it the DataKeys[row.RowIndex] or is it Values[0]? My suspicion is that it's the latter - in other words, you don't actually have a value in there.

                                    N 2 Replies Last reply
                                    0
                                    • P Pete OHanlon

                                      Now that you know the line, you need to identify which part is the problem. Is it the DataKeys[row.RowIndex] or is it Values[0]? My suspicion is that it's the latter - in other words, you don't actually have a value in there.

                                      N Offline
                                      N Offline
                                      Norris Chappell
                                      wrote on last edited by
                                      #18

                                      I don't see the out of range error anymore. It doesn't update but deletes the first record in the database. I getting this error: The variable name '@id' has already been declared. Variable names must be unique within a query batch or stored procedure.

                                      1 Reply Last reply
                                      0
                                      • P Pete OHanlon

                                        Now that you know the line, you need to identify which part is the problem. Is it the DataKeys[row.RowIndex] or is it Values[0]? My suspicion is that it's the latter - in other words, you don't actually have a value in there.

                                        N Offline
                                        N Offline
                                        Norris Chappell
                                        wrote on last edited by
                                        #19

                                        It appears I don't because I not getting that OOR error any more. I getting:The variable name '@id' has already been declared. Variable names must be unique within a query batch or stored procedure. Do I need to make any field Label instead of TextBox, The ID field is being is being hidden. I really don't know what is wrong now. Here is my present code. Maybe by looking at all of the code you might can spot something I missed. I have been working on this 4 straight days.

                                        using System;
                                        using System.Data;
                                        using System.Collections.Generic;
                                        using System.Linq;
                                        using System.Web;
                                        using System.Web.UI;
                                        using System.Web.UI.WebControls;
                                        using System.Data.Sql;
                                        using System.Data.SqlClient;
                                        using System.Configuration;
                                        using System.Web.UI.WebControls.WebParts;

                                        namespace StaffingWebParts.KeyPerTest
                                        {
                                        public partial class KeyPerTestUserControl : UserControl
                                        {
                                        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString);
                                        SqlCommand cmd = new SqlCommand();

                                            protected void Page\_Load(object sender, EventArgs e)
                                            {
                                                if (!Page.IsPostBack)
                                                {
                                                    DataTable dt = new DataTable();
                                        
                                                    dt.Columns.Add("ID");
                                                    dt.Columns.Add("Name");
                                                    dt.Columns.Add("VDCIDIQ");
                                                    dt.Columns.Add("VDCFFS");
                                                    dt.Columns.Add("VDCHIM");
                                                    dt.Columns.Add("VDCWEBHOSTING");
                                                    dt.Columns.Add("VDCCWF");
                                                    SqlDataReader myReader = null;
                                                    SqlCommand cmd = new SqlCommand("SELECT ID, Name, VDCIDIQ , VDCFFS, VDCHIM, VDCWEBHOSTING, VDCCWF  from CMS\_Key\_Personnel where Name <> '   ' order by  Name");
                                                    cmd.Connection = conn;
                                                    conn.Open();
                                                    myReader = cmd.ExecuteReader();
                                                    while (myReader.Read())
                                                    {
                                                        DataRow dr = dt.NewRow();
                                                        dr\[0\] = myReader\["ID"\].ToString();
                                                        dr\[1\] = myReader\["Name"\].ToString();
                                                        dr\[2\] = myReader\["VDCIDIQ"\].ToString();
                                                        dr\[3\] = myReader\["VDCFFS"\].ToString();
                                                        dr\[4\] = myReader\["VDCHIM"\].ToString();
                                                        dr\[5\] = myReader\["VDCWEBHOSTING"\].ToString();
                                                        dr\[6\] = myReader\["VDCCWF"\].ToString();
                                                        dt.Rows.Add(dr);
                                                    }
                                                    
                                                    gvKeyPersonnel.DataSource = dt;
                                        
                                        P 1 Reply Last reply
                                        0
                                        • N Norris Chappell

                                          It appears I don't because I not getting that OOR error any more. I getting:The variable name '@id' has already been declared. Variable names must be unique within a query batch or stored procedure. Do I need to make any field Label instead of TextBox, The ID field is being is being hidden. I really don't know what is wrong now. Here is my present code. Maybe by looking at all of the code you might can spot something I missed. I have been working on this 4 straight days.

                                          using System;
                                          using System.Data;
                                          using System.Collections.Generic;
                                          using System.Linq;
                                          using System.Web;
                                          using System.Web.UI;
                                          using System.Web.UI.WebControls;
                                          using System.Data.Sql;
                                          using System.Data.SqlClient;
                                          using System.Configuration;
                                          using System.Web.UI.WebControls.WebParts;

                                          namespace StaffingWebParts.KeyPerTest
                                          {
                                          public partial class KeyPerTestUserControl : UserControl
                                          {
                                          SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString);
                                          SqlCommand cmd = new SqlCommand();

                                              protected void Page\_Load(object sender, EventArgs e)
                                              {
                                                  if (!Page.IsPostBack)
                                                  {
                                                      DataTable dt = new DataTable();
                                          
                                                      dt.Columns.Add("ID");
                                                      dt.Columns.Add("Name");
                                                      dt.Columns.Add("VDCIDIQ");
                                                      dt.Columns.Add("VDCFFS");
                                                      dt.Columns.Add("VDCHIM");
                                                      dt.Columns.Add("VDCWEBHOSTING");
                                                      dt.Columns.Add("VDCCWF");
                                                      SqlDataReader myReader = null;
                                                      SqlCommand cmd = new SqlCommand("SELECT ID, Name, VDCIDIQ , VDCFFS, VDCHIM, VDCWEBHOSTING, VDCCWF  from CMS\_Key\_Personnel where Name <> '   ' order by  Name");
                                                      cmd.Connection = conn;
                                                      conn.Open();
                                                      myReader = cmd.ExecuteReader();
                                                      while (myReader.Read())
                                                      {
                                                          DataRow dr = dt.NewRow();
                                                          dr\[0\] = myReader\["ID"\].ToString();
                                                          dr\[1\] = myReader\["Name"\].ToString();
                                                          dr\[2\] = myReader\["VDCIDIQ"\].ToString();
                                                          dr\[3\] = myReader\["VDCFFS"\].ToString();
                                                          dr\[4\] = myReader\["VDCHIM"\].ToString();
                                                          dr\[5\] = myReader\["VDCWEBHOSTING"\].ToString();
                                                          dr\[6\] = myReader\["VDCCWF"\].ToString();
                                                          dt.Rows.Add(dr);
                                                      }
                                                      
                                                      gvKeyPersonnel.DataSource = dt;
                                          
                                          P Offline
                                          P Offline
                                          Pete OHanlon
                                          wrote on last edited by
                                          #20

                                          The reason you're getting this exception is because you're attempting to add the parameters to the same command object inside a loop. This will work on the first trip through the loop, but will fail on the next trip through. A way around this is to do cmd.Parameters.Clear(); before you start adding the parameters in. This will ensure the parameters collection has no entries on each journey through the loop.

                                          N 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