Trouble writing to database in C# WinForm Application

calendar_today Asked Jul 3, 2013
thumb_up 7 upvotes
history Updated April 14, 2026

Direct Answer

There are many problems in your code above. First, a command should be executed, not simply declared. (this is why the database is not being modified) Second, you use reserved…. This is a 20-line Access VBA snippet, ranked #67th of 67 by community upvote score, from 2013.


The Problem (Q-score 3, ranked #67th of 67 in the Access VBA archive)

The scenario as originally posted in 2013

I’m relatively inexperienced with professional programming, but I’m trying to write a program that interfaces with a MS Access Database. Essentially I’m gathering information in the form and trying to pass information at a new line for each entry. I have an open OleDbConnection and my test is showing that I am able to see what row will have the new entry, but when I hit the submit button, there is no error shown in the catch, but the database remains unchanged. I originally had the code in a method that I called from the click event, but I just brought the code over to the event handler to verify the issue wasn’t with the call.

private void btnSubmit_Click(object sender, EventArgs e)
    {

        if (DBConnection.State.Equals(ConnectionState.Closed))
        {
            DBConnection.Open();
        }

        try
        {
            MessageBox.Show("Save Data at index: " + intRowPosition.ToString());

            OleDbCommand OledbInsert = new OleDbCommand("Insert INTO RetentionTable (DateTime,Center,CSP,MemberID,ContractNumber,RetentionType,RetentionTrigger,MemberReason,ActionTaken,Other) VALUES('" + DateTime.Now.ToString() + "','" + GetCenter("") + "','" + GetName("") + "','" + GetMemberID("") + "','" + GetContractNumber("") + "','" + GetType("") + "','" + GetTrigger("") + "','" + GetReason("") + "','" + GetAction("") + "', + GetOther("")," DBConnection);

            intRowPosition++;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
            MessageBox.Show(ex.StackTrace.ToString());
        }
        finally
        {
            RefreshDBConnection();
        }

    }

Any ideas as to why this is not writing would be much appreciated.

Why community consensus is tight on this one

Across 67 Access VBA entries in the archive, the accepted answer here holds niche answer (below median) status — meaning voters are unusually aligned on the right fix.


The Verified Solution — niche answer (below median) (+7)

20-line Access VBA pattern (copy-ready)

There are many problems in your code above.

  • First, a command should be executed, not simply declared. (this is why the database is not being modified)
  • Second, you use reserved keywords in your statement (so even if you execute your statement, it will fail and throw an exception)
  • Third, you are concatenating strings to build the command text. A
    very bad move that would leave your application susceptible to SQL injection attacks
  • Fourth, the connection should be closed after usage

Let me try to write a replacement code

string cmdText = "Insert INTO RetentionTable " +
                "([DateTime],Center,CSP,MemberID,ContractNumber,RetentionType," + 
                "RetentionTrigger,MemberReason,ActionTaken,Other) " + 
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
 using(OleDbConnection cn = new OleDbConnection(conString))
 using(OleDbCommand cmd = new OleDbCommand(cmdText, cn))
 {
    cmd.Parameters.AddWithValue("@p1", DateTime.Now.ToString());
    cmd.Parameters.AddWithValue("@p2", GetCenter("")); 
    cmd.Parameters.AddWithValue("@p3", GetName(""));
    cmd.Parameters.AddWithValue("@p4", GetMemberID(""));
    cmd.Parameters.AddWithValue("@p5", GetContractNumber(""));
    cmd.Parameters.AddWithValue("@p6", GetType("")); 
    cmd.Parameters.AddWithValue("@p7", GetTrigger(""));
    cmd.Parameters.AddWithValue("@p8", GetReason(""));
    cmd.Parameters.AddWithValue("@p9", GetAction(""));
    cmd.Parameters.AddWithValue("@p10", GetOther(""));
    cmd.ExecuteNonQuery();
 }

The DATETIME is a reserved keyword in Access and thus, if you want to use it for your column names then you need to enclose it in square brackets.

The string concatenation is a bad practice in MSAccess but it is a fatal flaw in other database where your code could be used for Sql Injections (more difficult in Access but not impossible). If you use a parameterized query as in my example, you remove the Sql Injection problem, but also you let the framework code to pass the correct value to the database engine with the correct formatting required for dates, strings and decimals.

Another point to consider is to not have a global OleDbConnection object, but create, use and destroy the object whenever your need it. The Connection Pooling will avoid performance problems and your code will not suffer from memory leaks when a connection fails for whatever reason

I want also add that your GetXXXXX methods seems all to return strings. Remember that these methods should return values compatible with the underlying database field where you want to write


When to Use It — classic (2013–2016)

Ranked #67th in its category — specialized fit

This pattern sits in the 77% tail relative to the top answer. Reach for it when your scenario closely matches the question title; otherwise browse the Access VBA archive for a higher-consensus alternative.

What changed between 2013 and 2026

The answer is 13 years old. The Access VBA object model has been stable across Office 2013, 2016, 2019, 2021, 365, and 2024/2026 LTSC, so the pattern still compiles. Changes that might affect you: 64-bit API declarations (use PtrSafe), blocked macros in downloaded files (Mark-of-the-Web), and the shift toward Office Scripts for web-first workflows.

help
Frequently Asked Questions

This is a below-median answer — when does it still fit?
expand_more

Answer score +7 vs the Access VBA archive median ~4; this entry is niche. The score plus 3 supporting upvotes on the question itself (+3) means the asker and 6 subsequent voters all validated the approach.

Does the 20-line snippet run as-is in Office 2026?
expand_more

Yes. The 20-line pattern compiles on Office 365, Office 2024, and Office LTSC 2026. Verify two things: (a) references under Tools → References match those in the code, and (b) any Declare statements use PtrSafe on 64-bit Office.

Published around 2013 — what’s changed since?
expand_more

Published 2013, which is 13 year(s) before today’s Office 2026 build. The Access VBA object model has had no breaking changes in that window. Three things to re-test: (1) blocked macros on downloaded files (Mark-of-the-Web), (2) 64-bit API declarations (PtrSafe, LongPtr), (3) any shift toward Office Scripts for web scenarios.

Which Access VBA pattern ranks just above this one at #66?
expand_more

The pattern one rank above is “Invalid Use of Property?”. If your use case overlaps, compare both before committing.

Data source: Community-verified Q&A snapshot. Q-score 3, Answer-score 7, original post 2013, ranked #67th of 67 in the Access VBA archive. Last regenerated April 14, 2026.