无法在表格中看到我的数据

时间:2012-03-29 10:31:36

标签: c# wpf sql-server

我正在使用Sql Connection创建一个简单的WPF应用程序。问题是,当我调试 程序似乎没问题(没有错误),但我无法在数据库中看到我的数据。

private void button1_Click(object sender, RoutedEventArgs e)
    {
        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();

        conn.ConnectionString = @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MIKE.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

        try
        {
            SqlCommand SqlCmd = new System.Data.SqlClient.SqlCommand("INSERT INTO [Customer](FirstName,LastName) VALUES(@FirstName,@LastName)", conn);

            conn.Open();

            // Insert code to process data.
            SqlCmd.Parameters.AddWithValue("@FirstName", CUCFirstName.Text);
            SqlCmd.Parameters.AddWithValue("@LastName", CUClastName.Text);

            SqlCmd.ExecuteNonQuery();

        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message, ex.Number.ToString());
        }
        finally
        {
            conn.Close();
        }
    }

和我的xaml代码

 <Grid>
    <Button Content="Add" Height="66" HorizontalAlignment="Left" Margin="324,233,0,0" 
            Name="button1" VerticalAlignment="Top" 
            Width="135" Click="button1_Click" />

    <TextBox Height="36" HorizontalAlignment="Left" Margin="74,32,0,0" Name="CUCFirstName" 
             VerticalAlignment="Top" Width="242">
    </TextBox>

    <TextBox Height="39" HorizontalAlignment="Left" Margin="74,74,0,0" Name="CUClastName" 
             VerticalAlignment="Top" Width="242">
    </TextBox>

    <Label Content="First Name" Height="33" HorizontalAlignment="Left" Margin="324,32,0,0" 
           Name="label1" VerticalAlignment="Top" Width="151" />

    <Label Content="Last Name" Height="34" HorizontalAlignment="Left" Margin="324,72,0,0" 
           Name="label2" VerticalAlignment="Top" Width="151" />
</Grid>

1 个答案:

答案 0 :(得分:0)

每次运行应用程序时,数据库的新实例都会复制到调试文件夹中(因为它被视为资源)。将数据库放在本地硬盘驱动器中的某些位置,如“C:\ Test”并指定连接字符串中的路径相同。