Easy Visual Studio C# database example using a local dynamically created database ("LocalDB")

This is more straightforward than trying to use sqlite, and sqlserverce has been deprecated


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace test_create_database_as_mdf_file
{
    public partial class Form1 : Form
    {
        SqlConnection conn;

        public  void CreateSqlDatabase(string filename)
        {
            string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
            conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
            conn.Open();
            using (var command = conn.CreateCommand())
            {
                command.CommandText = String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
                command.ExecuteNonQuery();
                command.CommandText = String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
                command.ExecuteNonQuery();
            }

            /* The code above does the work inside 'master' catalog.  If I use this same connection to create tables they also are created there, so
            now that the database has been created and detached, it must be re-attached to then create tables and such,  and use it...*/

            conn = new SqlConnection(String.Format(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename={0}",filename));
            conn.Close();            
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                CreateSqlDatabase(openFileDialog1.FileName);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            conn.Open();
            SqlCommand comm = conn.CreateCommand();
            comm.CommandText = "create table mytable (id int, name nvarchar(100))";
            comm.ExecuteNonQuery();
            comm.CommandText = "insert into mytable (id,name) values (10,'testing')";
            comm.ExecuteNonQuery();
            comm.CommandText = "select * from mytable";
            SqlDataReader reader = comm.ExecuteReader();

            while (reader.Read())
            {
                textBox1.Text += reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
            }
            conn.Close();

        }
    }
}