Inserting Data into a Table Using C# Windows Forms Application

Inserting Data into a Table Using C# Windows Forms Application

In this article, we will discuss how to insert data into a table using a C# Windows Forms application. We will go through the steps of creating a connection string, opening a database connection, and executing SQL commands.

Understanding the Basics

Before we dive into the code, it’s essential to understand the basics of the technology involved:

Connection Strings

A connection string is a piece of text that identifies a data source and specifies the protocol to use when connecting to it. In this case, we will be using a SQL Server connection string.

SQL Commands

SQL (Structured Query Language) is a language used to manage relational databases. SQL commands are used to perform various operations on data in the database, such as inserting, updating, or deleting data.

Creating a Connection String

The first step in connecting to a database is to create a connection string. A connection string typically includes the following components:

  • The data source (e.g., server name, database name)
  • The protocol used to connect to the data source (e.g., SQL Server)
  • The username and password for authentication
  • Other settings specific to the data source

In our example, we will be using a pre-configured connection string provided by the application’s properties settings.

Creating a Database Connection

Once we have created a connection string, we can use it to establish a database connection. This involves creating a new instance of the SqlConnection class and passing the connection string to its constructor.

// Create a new instance of SqlConnection
SqlConnection sqlConnection = new SqlConnection(con_string);

// Open the database connection
sqlConnection.Open();

Executing SQL Commands

To execute an SQL command, we need to create a new instance of the SqlCommand class and pass the SQL command as a string to its constructor. We can then add parameters to the command using the AddWithValue method.

// Create a new instance of SqlCommand
SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);

// Add parameters to the command
mycom.Parameters.AddWithValue("@Titel", textBox1.Text);
mycom.Parameters.AddWithValue("@Inerpret", textBox2.Text);

// Execute the SQL command
sqlConnection.Open();
mycom.ExecuteNonQuery();

Handling Errors

When working with database connections and SQL commands, it’s essential to handle errors that may occur during execution. We can use a try-catch block to catch any exceptions that are thrown.

try
{
    sqlConnection.Open();
    mycom.ExecuteNonQuery();
}
catch (SqlException ex)
{
    // Handle the error
    MessageBox.Show(ex.Message);
}

Show Results

After executing the SQL command, we need to show the results. We can do this by retrieving the data from the database using a DataTable or a DataGridView.

// Create a new instance of SqlDataAdapter
SqlDataAdapter da = new SqlDataAdapter(myselect, sqlConnection);

// Fill the DataTable with data
da.Fill(dt);

// Set the DataSource property of the DataGridView to the DataTable
dataGridView1.DataSource = dt;

Example Use Case

Here’s an example use case that demonstrates how to insert data into a table using C# Windows Forms application:

private void btnAdd_Click(object sender, EventArgs e)
{
    // Create a new instance of SqlConnection
    string con_string = "database connection string";
    SqlConnection sqlConnection = new SqlConnection(con_string);

    // Create the SQL command
    string myinsert = "insert into tab_Musik values (@Titel,@Inerpret)";
    SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);

    // Add parameters to the command
    mycom.Parameters.AddWithValue("@Titel", textBox1.Text);
    mycom.Parameters.AddWithValue("@Inerpret", textBox2.Text);

    try
    {
        // Open the database connection
        sqlConnection.Open();

        // Execute the SQL command
        mycom.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        // Handle the error
        MessageBox.Show(ex.Message);
    }

    // Clone and dispose of the SqlCommand object
    mycom.Clone();
    mycom.Dispose();
}

This example demonstrates how to create a connection string, establish a database connection, execute an SQL command, and handle errors.

Conclusion

In this article, we discussed how to insert data into a table using C# Windows Forms application. We covered the basics of creating a connection string, opening a database connection, executing SQL commands, handling errors, and showing results. With this knowledge, you should be able to create your own C# Windows Forms applications that interact with databases.

Additional Resources

By following the steps outlined in this article, you should be able to create a C# Windows Forms application that inserts data into a table. Remember to always handle errors and show results to ensure that your application provides a good user experience.

Troubleshooting Tips

  • Make sure to check the connection string for any typos or errors.
  • Verify that the database server is running and accepting connections.
  • Check for any SQL syntax errors in the command being executed.
  • Make sure to handle any exceptions that may occur during execution.

Last modified on 2025-04-23