How to connect to SQL Server using WPF and write data to a table?

To connect to SQL Server and write data to a table in a WPF application, you first need to install the NuGet package System.Data.SqlClient. Then, you can follow these steps:

  1. Create a form in the XAML file for entering data.
<StackPanel>
    <TextBox x:Name="txtName" Margin="5" Width="200" PlaceholderText="Name"/>
    <TextBox x:Name="txtEmail" Margin="5" Width="200" PlaceholderText="Email"/>
    <Button x:Name="btnSave" Content="Save" Click="btnSave_Click"/>
</StackPanel>
  1. Add event handlers for the connection string and save button click in the code file.
using System.Data.SqlClient;

private string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True";

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    string name = txtName.Text;
    string email = txtEmail.Text;

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        string query = "INSERT INTO YourTableName (Name, Email) VALUES (@Name, @Email)";

        using (SqlCommand command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@Name", name);
            command.Parameters.AddWithValue("@Email", email);

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }
}

In the code above, you need to replace YourServerName, YourDatabaseName, and YourTableName with the actual SQL Server server name, database name, and table name.

  1. Run the application, fill out the form data, and then click the save button to write the data into the SQL Server table.
bannerAds