locked
Update statement inserts a new row instead of updating RRS feed

  • Question

  • My code should just update a single specific row in the table. I used a simple procedure to update a record in the current application as well and it runs without any problem except this case. Every time the query runs, it actually inserts a new row instead of just updating an existing:

    So here is my c# code:

     try
            {
                command.Parameters.Clear();
                command.Parameters.AddRange(vars);
                command.CommandText = "Update" + tableName;
    
                conn.Open();
                command.ExecuteNonQuery();
                conn.Close();
    
                this.GetData(tableName);
            }
            catch
            {
                throw;
            }

    And here is my SQL code (please ingore 'Alter Procedure' statement, I just wanted to get the core script of the procedure):

     ALTER procedure [dbo].[UpdateExpenditureItems]
        (@ID int,
        @Name nvarchar(50),
        @IsGroup bit,
        @Parent nvarchar(50),
        @Description nvarchar(50)
        )
    
        AS
    
        Begin
    
    --a new inserted row seems to be a result of running IF statement rather than ELSE
        if @Parent is not null
            begin
            declare @ParentID int
    
            set @ParentID = (select ID from ExpenditureItems where Name=@Parent);
    
            UPDATE ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=@ID;
    
            end
        else
            begin
            UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=@ID
            end
        end

    I ran the query itself from sql management studio and it works fine. The problem seems to be in c# code, but there's nothing unusual. Same code for operations with the databse works fine in other parts of the software... I appreciate your help!

    Thanks in advance!


    Sunday, April 12, 2015 8:30 AM

Answers

  • With the help of other users I can post an asnwer here. The reason was that current form was inherited from the other and when I pressed the OK button, base class's OK button click event was fired first and then the child.

    Solution: either end up with running base class button click event OR use virtual and override to ovverride the base class method.

    • Marked as answer by Emil Huseynov Monday, April 13, 2015 11:48 AM
    Monday, April 13, 2015 11:48 AM

All replies

  • To update a row of the table the ID that you are passing must already be in the table. For some reason the IDs are not matching.  I would compare the type of parameter you are using in the C# application and make sure it is an a SqlDbType.Int (or equivalent).  I keep on warning people never to use AddWithValue() which doesn't include a parameter type.  When you use AddWithValue() without the type the Net library driver has to guess the type of variable and guesses wrong creating errors like what you are seeing.


    jdweng

    Sunday, April 12, 2015 11:58 AM
  • I can spot only two things:

    1. You're creating the name of the executed procedure dynammically. Maybe your using the wrong ine.
    2. When the T-SQL code is complete, then there is never a new row inserted. But you're may updating the wrong row.

    Cause

     set @ParentID = (select ID from ExpenditureItems where Name=@Parent);

    requires that Name is unique in your table. When it's not, then you'll get on arbitrary ID.

    Sunday, April 12, 2015 12:11 PM
  • this was how I used to create parameters:

    SqlParameter[] pars = new SqlParameter[5];
    
                pars[0] = new SqlParameter("@ID", int.Parse(idTB.Text));
                pars[1] = new SqlParameter("@Name", itemTB.Text);
                pars[2] = new SqlParameter("@IsGroup", true);
                pars[3] = new SqlParameter("@Parent", DBNull.Value);
                pars[4] = new SqlParameter("@Description", descTB.Text);

    And this is what I changed on your advice:

    SqlParameter[] pars = new SqlParameter[5];
    
                pars[0] = new SqlParameter("@ID", int.Parse(idTB.Text));
                pars[0].SqlDbType = SqlDbType.Int;
                pars[1] = new SqlParameter("@Name", itemTB.Text);
                pars[2] = new SqlParameter("@IsGroup", true);
                pars[3] = new SqlParameter("@Parent", DBNull.Value);
                pars[4] = new SqlParameter("@Description", descTB.Text);

    But the result is still the same. What am I doing wrong?

    Sunday, April 12, 2015 12:13 PM
  • Again, when I run the procedure from sql management itself, everything is correct. I'm trying to attach a screenshot now.


    Sunday, April 12, 2015 12:31 PM
  • Check the field in the database and make sure it is also an 'int'.  You may have it set to a 'nvarchar'.  Also check which field in the database is the primary key.  If there isn't one set the ID as the primary field.

    jdweng


    Sunday, April 12, 2015 12:53 PM
  • Since UPDATE never inserts new rows (unless there are some special “triggers” in SQL; however, they should be observed on manual execution too), re-check your code for possible INSERT commands and put some breakpoints. Perhaps, for some reason, the other portions, not shown in your sample, which insert the data, are executed unexpectedly.


    By the way, did not show the whole SQL code? It should be an END at the and.


    • Edited by Viorel_MVP Sunday, April 12, 2015 1:55 PM
    Sunday, April 12, 2015 1:51 PM
  • It's ok with ID. It is a primary key. and last 'end' is there. It would through an exception too if I would step into procedure from within sql.
    Sunday, April 12, 2015 4:35 PM
  • this procedure does not have INSERT statement at all. Only 2 UPDATE statements depending on ParentID value.
    Sunday, April 12, 2015 4:37 PM
  • Then maybe this.GetData(tableName) does not avoid visual duplication of rows. Did you check the database content using other tools, such as Management Studio?

    Sunday, April 12, 2015 4:53 PM
  • Did you check the field property to make sure it was an 'int'?

    jdweng

    Sunday, April 12, 2015 5:01 PM
  • Please can you post your full C# code for this function? Also the code you sent is not calling an SP? so why do we need to validate against the SP?

    Fouad Roumieh

    Sunday, April 12, 2015 5:03 PM
  • Then maybe this.GetData(tableName) does not avoid visual duplication of rows. Did you check the database content using other tools, such as Management Studio?

    Please see the code below.

    Monday, April 13, 2015 4:04 AM
  • Did you check the field property to make sure it was an 'int'?

    jdweng

    Yes, I did. It is a primary key set and 'int' field.
    Monday, April 13, 2015 4:05 AM
  • Please can you post your full C# code for this function? Also the code you sent is not calling an SP? so why do we need to validate against the SP?

    Fouad Roumieh

    So here is my code:

    //Update is called on OK button click
    private void okBut_Click(object sender, EventArgs e)
            {
                //edit code runs here
                SqlParameter[] pars = new SqlParameter[5];
    
    
                
                pars[0] = new SqlParameter("@ID", int.Parse(idTB.Text));
                pars[0].SqlDbType = SqlDbType.Int;
    
                
                pars[1] = new SqlParameter("@Name", itemTB.Text);
                pars[1].SqlDbType = SqlDbType.NVarChar;
    
                
                pars[2] = new SqlParameter("@IsGroup", true);
                pars[2].SqlDbType = SqlDbType.Bit;
                
                pars[3] = new SqlParameter("@Parent", DBNull.Value);
                pars[3].SqlDbType = SqlDbType.Int;
    
                
                pars[4] = new SqlParameter("@Description", descTB.Text);
                pars[4].SqlDbType = SqlDbType.NVarChar;
                
                
                try
                {
                    DAL dal = new DAL();
                    dal.UpdateData("ExpenditureItems", pars); //Update is called here
                }
                catch (Exception ex)
                {
                    StaticValues.WriteEventLogXML(ex, this.Text);
                    switch (StaticValues.user.Language)
                    {
                        case "English":
                            MessageBox.Show("Database error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        default:
                            break;
                    }
                }
                finally
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    StaticValues.currentNode = itemTB.Text;
                }
            }

    public void UpdateData(string tableNameString, SqlParameter[] vars)
            {
                string tableName = tableNameString.Replace(" ", string.Empty);
    
                try
                {
                    command.Parameters.Clear();
                    command.Parameters.AddRange(vars);
                    command.CommandText = "Update" + tableName;
    
                    conn.Open();
                    command.ExecuteNonQuery();
                    conn.Close();
    
                    this.GetData(tableName);
                }
                catch
                {
                    throw;
                }
            }

    And here is GetData procedure:

    public void GetData(string tableNameString)
            {
                string tableName = tableNameString.Replace(" ", string.Empty);
                command.CommandText = "Get" + tableName;
                command.Parameters.Clear();
    
                if (!StaticValues.dataSet.Tables.Contains(tableName))
                    StaticValues.dataSet.Tables.Add(tableName);
                else
                    StaticValues.dataSet.Tables[tableName].Clear();
    
                try
                {
                    adapter.SelectCommand = command;
                    conn.ConnectionString = DAL.ConnectionString;
                    command.Connection = conn;
                    conn.Open();
                    adapter.Fill(StaticValues.dataSet.Tables[tableName]);
                    conn.Close();
                }
                catch
                {
                    throw;
                }
            }

    And this is my complete code for sql procedure:

    USE [ISWM project]
    GO
    /****** Object:  StoredProcedure [dbo].[UpdateExpenditureItems]    Script Date: 13.04.2015 9:09:36 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[UpdateExpenditureItems]
    (@ID int,
    @Name nvarchar(50),
    @Parent nvarchar(50),
    @Description nvarchar(50),
    @IsGroup bit
    )
    
    AS
    
    Begin
    
    if @Parent IS NOT null
    	begin
    	declare @ParentID int
    
    	set @ParentID = (select ID from ExpenditureItems where Name=@Parent);
    
    	UPDATE ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=@ID;
    
    	end
    else
    	begin
    	UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=@ID
    	end
    end

    The codes posted above work great in other similar parts of the application where select, insert, delete and update is required.

    Concerning my current problem - I ran the procedure itself in SQL Server Management Studio, and it works well. I would say that there's something wrong with my c# code, but it can't be wrong because it's quite simple and works in other place in my application... I really don't get what's missing...



    Monday, April 13, 2015 4:12 AM
  • Thank you. I don't see any where condition in your update query. 

    command.CommandText = "Update" + tableName;


    Fouad Roumieh

    Monday, April 13, 2015 5:34 AM
  • I think you mixing here between the query form the code and your SP, your code is not calling the SP sent its running its own SQL query that has no where condition. If you want to call the SP to perform the udpate, change your code to :

     		command.Parameters.Clear();
                    command.Parameters.AddRange(vars);
    		command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "UpdateExpenditureItems"; 

    You have to sycn one of the parameter types, in code(int) its different from SP(nvarchar):

     pars[3] = new SqlParameter("@Parent", DBNull.Value);
                pars[3].SqlDbType = SqlDbType.Int;


    Fouad Roumieh



    Monday, April 13, 2015 5:51 AM
  • Yes, Fouad, you are right, that I should have pointed out the CommandType. However it helped me neither. It still adds a new row with a new ID

    Unfortunately due to account verification I cannot post a screenshot here neither can I post links to an external image. Here's a link to the screenshot:

    http://imgbin.org/index.php?page=image&id=23315

    As you see, the ID of the row which should be updated is assigned to Parent field of the new row.




    Monday, April 13, 2015 6:03 AM
  • Not only the command type also the command text, please post the updated version of the method from your side. Did you fix the parameter type issue also?


    Fouad Roumieh


    Monday, April 13, 2015 6:07 AM

  • I see, can you pass the id value as static in your query now and see what will happen, and call again from your code (make sure that 3127 row is not deleted):

    UPDATE ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=3127;


    Please post your updated method code.

    Fouad Roumieh



    Monday, April 13, 2015 6:24 AM
  • //Update is called on OK button click
    private void okBut_Click(object sender, EventArgs e)
            {
                //edit code runs here
                SqlParameter[] pars = new SqlParameter[5];
    
    
                
                pars[0] = new SqlParameter("@ID", int.Parse(idTB.Text));
                pars[0].SqlDbType = SqlDbType.Int;
    
                
                pars[1] = new SqlParameter("@Name", itemTB.Text);
                pars[1].SqlDbType = SqlDbType.NVarChar;
    
                
                pars[2] = new SqlParameter("@IsGroup", true);
                pars[2].SqlDbType = SqlDbType.Bit;
                
                pars[3] = new SqlParameter("@Parent", DBNull.Value);
    	    pars[3].SqlDbType = SqlDbType.NVarChar;
    
                
                pars[4] = new SqlParameter("@Description", descTB.Text);
                pars[4].SqlDbType = SqlDbType.NVarChar;
                
                
                try
                {
                    DAL dal = new DAL();
                    dal.UpdateData("ExpenditureItems", pars); //Update is called here
                }
                catch (Exception ex)
                {
                    StaticValues.WriteEventLogXML(ex, this.Text);
                    switch (StaticValues.user.Language)
                    {
                        case "English":
                            MessageBox.Show("Database error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        default:
                            break;
                    }
                }
                finally
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    StaticValues.currentNode = itemTB.Text;
                }
            }

    And Update code revised as you advised:

    public void UpdateData(string tableNameString, SqlParameter[] vars)
            {
                string tableName = tableNameString.Replace(" ", string.Empty);
    
                try
                {
                    command.Parameters.Clear();
                    command.Parameters.AddRange(vars);
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "UpdateExpenditureItems";
    
                    conn.Open();
                    command.ExecuteNonQuery();
                    conn.Close();
    
                    this.GetData(tableName);
                }
                catch
                {
                    throw;
                }
            }


    Monday, April 13, 2015 6:27 AM
  • Here is the sreenshot from SSMS

    http://imgbin.org/index.php?page=image&id=23315

    Monday, April 13, 2015 6:28 AM
  • Fouad, I tried that. It did the same.
    Monday, April 13, 2015 6:35 AM
  • I'm sorry that should be done in the second update query because you passing ParentID as null:

    UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=3127
    	end
    Please give it another try.


    Fouad Roumieh

    Monday, April 13, 2015 6:38 AM
  • Yes, Fouad, I noticed that and changed accordingly. No help... Maybe I should just put UPDATE query directly to c# code and switch to CommandType.CommandText... But this issue won't let me sleep!

    btw, did you manage to view screenshot?

    Monday, April 13, 2015 6:41 AM
  • Yes I saw, and its showing like its going into the first if option because it is selecting the parentid 3127.

    • You need to isolate your code from that form to a new form/application, only the code you've sent. Is it windows or web app? and you have to execute only that function by passing static values into the params.
    • Please send us the create table script to be able to reproduce the same.
    • Please confirm again that no triggers are there on that table.
    • one more thing also is change you SP to only one update statment as below and execute the code again
    USE [ISWM project]
    GO
    /****** Object:  StoredProcedure [dbo].[UpdateExpenditureItems]    Script Date: 13.04.2015 9:09:36 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[UpdateExpenditureItems]
    (@ID int,
    @Name nvarchar(50),
    @Parent nvarchar(50),
    @Description nvarchar(50),
    @IsGroup bit
    )
    
    AS
    
    Begin
    
    UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=@ID
    
    end 



    Fouad Roumieh





    Monday, April 13, 2015 6:47 AM
    • It is a windows app. Yes, I can set it with static values, but I still wonder why SP should not work...
    • Here is create table script:

    USE [ISWM project]
    GO
    
    /****** Object:  Table [dbo].[ExpenditureItems]    Script Date: 13.04.2015 11:50:15 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE TABLE [dbo].[ExpenditureItems](
    	[ID] [int] IDENTITY(1,1) NOT NULL,
    	[Name] [nvarchar](50) NOT NULL,
    	[Parent] [int] NULL,
    	[Description] [nvarchar](50) NULL,
    	[IsGroup] [bit] NOT NULL,
     CONSTRAINT [PK_ExpenditureItems] PRIMARY KEY CLUSTERED 
    (
    	[ID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    

    • Triggers. I have never worked with triggers. But I suppose that they should be located in 'Database triggers' folder of every single database in SSMS. So this folders is empty. Is there any other places which I must check?
    Monday, April 13, 2015 6:54 AM
  • Don't worry we will get it to work :), please try the last option sent in my previous post and let me know.

    When you calling the SP from SQL and its working how you calling it? can you send the command please.


    Fouad Roumieh

    Monday, April 13, 2015 6:58 AM
  • Since the parentid in your db is int please do the related changes for that in your code:

    pars[3] = new SqlParameter("@Parent", DBNull.Value);
    	    pars[3].SqlDbType = SqlDbType.Int;

    and also in your SP:

    @Parent int,

    Also what is this condition in your SP setting name as parent, both are different datatypes

    set @ParentID = (select ID from ExpenditureItems where Name=@Parent);
    Please fix these issues before proceeding on this.


    Fouad Roumieh



    Monday, April 13, 2015 7:21 AM
  • Please review many updates in previous post.

    Fouad Roumieh

    Monday, April 13, 2015 7:37 AM
  • Fouad, this code runs fine in SSMS:

    declare @ID int
    declare @Name nvarchar(50)
    declare @Parent nvarchar(50)
    declare @Description nvarchar(50)
    declare @IsGroup bit
    
    
    Begin
    
    if @Parent IS NOT null
    	begin
    	declare @ParentID int
    
    	set @ParentID = (select ID from [ISWM project].dbo.ExpenditureItems where Name=@Parent);
    
    	UPDATE [ISWM project].dbo.ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=3127;
    
    	end
    else
    	begin
    	UPDATE [ISWM project].dbo.ExpenditureItems SET Name =@Name, Parent = NULL, [Description] =@Description, IsGroup = 1 WHERE ID=@ID
    	end
    end
    

    Now I'm going to try you previous post.

    Monday, April 13, 2015 7:42 AM
  • If we are talking about my first SP with conditions and  2 updates, then I declared a variable @Parent with type nvarchar. That's why it was set as nvarchar in pars. Then on the basis of @Parent I was looking for @ParentID.


    Monday, April 13, 2015 7:47 AM
  • I don't know what parameters did you pass but I want you to execute as below, after fixing the parentid data type:

    EXEC UpdateExpenditureItems 3127,'items',null,'Desc new',1


    Fouad Roumieh


    Monday, April 13, 2015 7:48 AM
  • Is this the entire script? No additional indices or constraints?

    Then your procedure will behave not correctly. Cause your table allows multiple rows having the same name value. Thus you may work with only one arbitrary row.

    You need an UNIQUE constraint.

    Monday, April 13, 2015 7:51 AM
  • If we are talking about my first SP with conditions and  2 updates, then I declared a variable @Parent with type nvarchar. That's why it was set as nvarchar in pars. Then on the basis of @Parent I was looking for @ParentID.


    So you mean Parent is not ParentID? whats the difference here? this is getting us into confusion.

    Fouad Roumieh

    Monday, April 13, 2015 7:52 AM
  • Yes, Fouad, EXEC worked.
    Monday, April 13, 2015 7:52 AM
  • This shows EXACTLY the problem I've already described as 2) in my first post.

    Monday, April 13, 2015 7:53 AM
  • Cool, try this condition now in your sp instead and call again from the code:

    if @Parent<>''
    Could be also != '' what is your sql version?


    Fouad Roumieh


    Monday, April 13, 2015 7:55 AM
  • Also try the below and see if it will create a new row:

    EXEC UpdateExpenditureItems 3127,'items','abc','Desc new',1


    Fouad Roumieh

    Monday, April 13, 2015 8:04 AM
  • Just to remind you that this is a treeview table.

    Let's forget Parent issue for now and proceed with the simpler code:

    USE [ISWM project]
    GO
    /****** Object:  StoredProcedure [dbo].[UpdateRootExpenditureItem]    Script Date: 13.04.2015 13:01:54 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[UpdateRootExpenditureItem]
    (
    @ID int,
    @Name nvarchar(50),
    @Description nvarchar(50)
    )
    
    as
    
    begin
    
    update ExpenditureItems set Name = @Name, [Description] = @Description where ID=@ID
    
    end

    and this works from within SSMS:

    EXEC UpdateRootExpenditureItem 3127,'Items','Desc new'

    sql version is 2012


    Monday, April 13, 2015 8:06 AM
  • I'm worried that the Parent is the issue, and maybe on the if condition its receiving empty string '' instead of null which will make it get into first option. Please revert back your SP and execute and see if new row is created:

    EXEC UpdateExpenditureItems 3127,'items','','Desc new',1


    Fouad Roumieh


    Monday, April 13, 2015 8:10 AM
  • Yes, it worked too. But it is not because of the Parent because when I simplified the code by removing the 'Parent's, behavior was just the same - works from within SSMS, and not from c#.
    Monday, April 13, 2015 8:18 AM
  • I asked to revert it back to it previous state and try.

    Fouad Roumieh

    Monday, April 13, 2015 8:20 AM
  • I did revert it back. It does not create a new row and updates row 3127.
    Monday, April 13, 2015 8:27 AM
  • What is the parent condition inside SP now, is it on null or ''? Can you call again from the code with both values. Sorry, I'm asking for that since I'm unable to reproduce at the moment.

    Fouad Roumieh

    Monday, April 13, 2015 8:30 AM
  • It is NULL. I'm passing the NULL value to @Parent as DBNull.Value. And now if @Parent is NULL then ELSE statement is execued, otherwise IF.

    p.s. I tried to insert update statement (see below) with static values directly to c# code and it again inserted a new row...

    command.CommandText = "Update ExpenditureItems Set Name = 'TEST ROOT', '', [Description] = 'Test descr', 1 WHERE ID = 3127";

    Monday, April 13, 2015 8:50 AM
  • This query is missing IsGroup column at the end, this should break are you debugging at the same time. Do you have any code to insert into that table in the form/app?

    Fouad Roumieh

    Monday, April 13, 2015 8:55 AM
  • Sorry, that was wrong code. But what I have FOUND - a new row is inserted even BEFORE UPDATE is called! What is this???
    Monday, April 13, 2015 9:02 AM
  • I have set a breakpoint on a very fisrt row of OK click. When I enter a new name for that item and click OK I found that a new row with a new name that I have entered is inserted as a new row. And when I delete that new row and continue to debug, update runs quite well!
    Monday, April 13, 2015 9:08 AM
  • I don't know how its happening, because I don't have a full view of your code. Suggestion is to search for any insert into that table either through binding (datagrid...) or via calls like the one we dealing with and put breackpoints on and see if its fired. Did you try to seperate this code into seperate app/form and execute?


    Fouad Roumieh

    Monday, April 13, 2015 9:09 AM
  • I have set a breakpoint on a very fisrt row of OK click. When I enter a new name for that item and click OK I found that a new row with a new name that I have entered is inserted as a new row. And when I delete that new row and continue to debug, update runs quite well!
    What type of control is this? can you send a screenshot of your form?

    Fouad Roumieh

    Monday, April 13, 2015 9:13 AM
  • Yes, I did. I create a new project and ran from there and it works fine. Looks like something wrong with my code. But how a new row can be inserted immediately on button click even before any line of code is executed...
    Monday, April 13, 2015 9:20 AM
  • Fouad, I'm one step closer. My current form is inherited from another one. And it seems that the base form's procedure is called on click event. How can i make it to skip base class's events?
    • Marked as answer by Emil Huseynov Monday, April 13, 2015 11:09 AM
    • Unmarked as answer by Emil Huseynov Monday, April 13, 2015 11:45 AM
    Monday, April 13, 2015 9:36 AM
  • That will be guessing from my side, you need to post full code for this. Did you put a breakpoint on the insert and verified if it was called when clicking ok button?

    Fouad Roumieh

    Monday, April 13, 2015 9:48 AM
  • Yes, I did. Insert command is executed in the base form on OK button click. Is there a way to override it?
    Monday, April 13, 2015 9:55 AM
  • Send the the signature of the insert method in the base form?

    Fouad Roumieh

    Monday, April 13, 2015 10:00 AM
  • I'm sorry, never did this before. How can I do it?
    Monday, April 13, 2015 10:16 AM
  • I meant the code, send the code of that insert method being called on base form.

    Fouad Roumieh

    Monday, April 13, 2015 10:19 AM
  • this is ok button click procedure of the base form:

    private void okBut_Click(object sender, EventArgs e)
            {
                if (!this.isEdit)
                {
                    SqlParameter[] pars = new SqlParameter[4];
                    pars[0] = new SqlParameter("@Name", itemTB.Text);
                    pars[1] = new SqlParameter("@IsGroup", true);
    
                    DataRowView rv = groupCB.SelectedItem as DataRowView;
                    pars[2] = new SqlParameter("@Parent", rv.Row["Name"].ToString());
    
                    
                    pars[3] = new SqlParameter("@Description", descTB.Text);
    
                    try
                    {
                        DAL dal = new DAL();
                        dal.InsertData("ExpenditureItems", pars);
                    }
                    catch (Exception ex)
                    {
                        StaticValues.WriteEventLogXML(ex, this.Text);
                        switch (StaticValues.user.Language)
                        {
                            case "English":
                                MessageBox.Show("Database error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        StaticValues.currentNode = itemTB.Text;
                    }
                }    
            }

    Monday, April 13, 2015 10:28 AM
  • The ok button that you seeing in child form is inherited from the base form, clicking on it is firing the base form event. Why you running into this scenario here, form inheritnace?

    In this case set the isEdit var to true when loading the child form (load event) if it is supposed to do edit only so the below condition fails:

    private void okBut_Click(object sender, EventArgs e) { if (!this.isEdit) { } }


    But when debugging is it executing the okButtton event in Child Form?


    Fouad Roumieh

    Monday, April 13, 2015 10:59 AM
  • Another option is to use virtual, override on these buttons after changing its access modifier to protected:

    main form:

            protected virtual  void okBut_Click(object sender, EventArgs e)
            {
                
            }

    Child Form:

     protected override void okBut_Click(object sender, EventArgs e)
            {
            
            }


    Fouad Roumieh


    Monday, April 13, 2015 11:07 AM
  • Yes, you are right. For now I have just overridden the base class' method. Don't want to touch what is working:)

    Fouad, thank you for your precious help and time spent on this. I appreciate it very much!

     
    Monday, April 13, 2015 11:09 AM
  • Yes, that was exactly what I did:)
    Monday, April 13, 2015 11:16 AM
  • First of all, is it strange it runs, is there no error thrown. 

    You miss the setting of the commandtype.

    https://msdn.microsoft.com/en-us/library/system.data.common.dbcommand.commandtype(v=vs.110).aspx

    Secondly we are unaware of the method GetData (maybe a tableadapter). But if that fills you will recognise that as all the time adding of rows in the datatable, while nothing is done.

    In that case you can first clear the datatable.

    Maybe I'm parroting some others, I did not read every reply in this thread. Sorry then therefore.


    Success
    Cor



    Monday, April 13, 2015 11:18 AM
  • Fouad, I'm one step closer. My current form is inherited from another one. And it seems that the base form's procedure is called on click event. How can i make it to skip base class's events?

    Not so clever to mark such a reply from yourself as answer if you got so many replies.


    Success
    Cor


    Monday, April 13, 2015 11:21 AM
  • Not so clever to mark such a reply from yourself as answer if you got so many replies.


    Success
    Cor


    I agree, since this answer is confusing for other users. Hope moderators fix this if user didn't.

    Fouad Roumieh

    Monday, April 13, 2015 11:23 AM
  • With the help of other users I can post an asnwer here. The reason was that current form was inherited from the other and when I pressed the OK button, base class's OK button click event was fired first and then the child.

    Solution: either end up with running base class button click event OR use virtual and override to ovverride the base class method.

    • Marked as answer by Emil Huseynov Monday, April 13, 2015 11:48 AM
    Monday, April 13, 2015 11:48 AM
  • Well I agree, but that post was the most suitable to mark as an answer. But you are right, so I fix that in order not to confuse other users.

    Monday, April 13, 2015 11:49 AM
  • Hello,

    Good to hear you have a resolution. Looking at the post marked as answered it would appear that you might consider either/or marking any replies as helpful and also consider if there are any replies that actually gave you a solution to mark them as answered along with yours.

    Currently when others with the same issue come and read this thread they have no clue what the resolution was.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Monday, April 13, 2015 1:08 PM