最近公司让学WPF,在网上找了个例子,调了一下,在这儿跟大家分享,还存在许多问题,大家共同研究:

[url]参考:http://www.zhiweinet.com/jiaocheng/2008-06/855.htm[/url]

[b]首先是数据库连接上的一些问题:[/b]
一:装上SQLSERVER 2005,以前登录直接选择'Windows身份验证',并没有什么问题出现!可前段时间采用'SQLSERVER身份验证'去登录,随之的问题就来了.无论用什么方法就是一个结果出错! 出错的原因是:'用户 'sa' 登录失败。该用户与可信 SQL Server 连接无关联'

/// 具体的方法是:   1:打开SQL Server Manager管理器!在左面找到 ‘安全性’ 单击右键 选择‘新建”,“登录” 弹出一个对话框,在登录名中输入你的登录号,选择'SQLSERVER身份验证',并输入密码,可以把‘用户下次登录时必须修改密码’取消掉。 点击‘用户映射’,在右面选择要映射的数据库,并在前面打勾!在下面一栏中‘db-owner’和‘public’前面打勾。然后点击'状态'在右面栏中选中"授予"、“启用”,这两项一般是默认的,但如果默认的不是此两项必须改过来,不然是连不上的!点击‘确定’。
2:找到SQL服务器,在左栏中上面,单击右键,在弹出的菜单中选择“属性”命令。弹出一个对话框,单击“安全性”,在“服务器身份验证”下面选择“SQL SERVER和WINDOWS身份验证模式”,在前面打勾!记得这一步很重要,如果没有这一步你就别想登录成功!然后单击“确定”就可以了! 3:重新启动服务就可以选择SQL SERVER 身份验证模式登录了!输入刚才的用户名和密码就可以登录成功了!
二:
C#中的字符串,如正则表达式中,有可能出现一些与C#语言相同的字符,比如"\",会让编译器作为C#语言来识别,截断该字符串,并可能产生编译器错误.
为了防止这种情况的发生,在该字符串前加一个"@"就是告诉编译器,这些特殊字符是作为字符串中的一部分存在的,编译器就不会去编译它了.
比如路径"c:\abc\d.txt"将产生编译器错误,之前可以写为"@c:\abc\d.txt"便得到其真实路径了.

[b]下面是关于WPF的例子:[/b]

[b]数据库:Test[/b]表:t_admin,person
t_admin(pId,pPwd)字段都是字符型的
person(ContactId,FirstName,LastName,EmailAddress)字段都是字符型的


登陆窗口Window2.xaml:

<Window x:Class="WPFTest.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="登陆界面" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="27*" />
            <RowDefinition Height="175*" />
            <RowDefinition Height="60*" />

        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Background="BlueViolet">
            <TextBlock Grid.Row="0"  HorizontalAlignment="Center"  Height="25" Name="title" Width="auto"  Text="登陆界面" FontSize="16" />      
        </StackPanel>

        <WrapPanel Grid.Row="1" Orientation="Horizontal" Margin="0,10,0,0">
            <StackPanel Height="37" Margin="0,13,0,0" Name="stackPanel1" VerticalAlignment="Top"   Orientation="Horizontal">
            <TextBlock Height="25" Name="textBlock1" Width="75"  Text=" 用户ID:"/>
            <TextBox Name="userID" Width="182" Height="26" />
        </StackPanel>
        <StackPanel Margin="0,13,0,10" Name="stackPanel2"  Orientation="Horizontal">
            <TextBlock Height="25" Name="textBlock2" Width="75"  Text=" 密码:"/>
            <PasswordBox Height="26" Name="userPwd" Width="182" />
        </StackPanel>

         <Label Height="26" Name="errMess" Width="268" Visibility="Hidden"></Label>

        </WrapPanel>

        <Button Grid.Row="2" Margin="84,13,111,10" Name="btnLogin" Click="btnLogin_Click" >登陆</Button>
        <Button Grid.Row="2" HorizontalAlignment="Right" Margin="0,13,10,12" Name="button1" Width="81" Click="button1_Click">关闭</Button>
    </Grid>
</Window>



对应的Window2.xaml.cs代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using ;
using .Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;


namespace WPFTest
{
    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
            this.errMess.Visibility = Visibility.Hidden;

        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection myConn = null;
            try
            {
                myConn = this.createConn();
                myConn.Open();

                string uid = this.userID.Text.Trim();
                string upwd = this.userPwd.Password;

                string mySql = "select count(*) from dbo.T_admin where pID = '" + uid+"' and pPwd = '"+upwd+"'";
                SqlCommand cmd = new SqlCommand(mySql, myConn);

                int count = Convert.ToInt32(cmd.ExecuteScalar());

                if (count > 0)
                {
                    //隐藏登陆界面,显示查询界面
                    this.Hide();
                    Window win1 = new Window1();
                    win1.Show();
                }
                else
                {
                    this.errMess.Visibility = Visibility.Visible;
                    this.errMess.Content = "登陆失败!";
                }

            }

            finally 
            {
                myConn.Close();
            }

        }

        private SqlConnection createConn() 
        {
            SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;database=Test;uid=login;password=login");
            //SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Test.MDF;Integrated Security=True;User Instance=True"); 
            return conn;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

    }
}



数据的增删改查界面Window1.xaml:


<Window x:Class="WPFTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="查询界面" Height="300" Width="300" IsEnabled="True">
    <Grid Background="Aquamarine" Opacity="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="auto" MinHeight="100" />
            <RowDefinition Height="22" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions >

        </Grid.ColumnDefinitions>

            <ListView  Height="280"  Name="listView1" VerticalAlignment="Top"  MinWidth="280" SelectionChanged="listView1_SelectionChanged">
            <ListView.View >
                <GridView x:Name="gridView1">
                    <GridViewColumn  Header="ContactID" DisplayMemberBinding="{Binding Path=ContactID}" ></GridViewColumn >
                    <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding Path=FirstName}"></GridViewColumn>
                    <GridViewColumn Header="LastName" DisplayMemberBinding="{Binding Path=LastName}"></GridViewColumn>
                    <GridViewColumn Header="EmailAddress" DisplayMemberBinding="{Binding Path=EmailAddress}"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView> 
        <WrapPanel Grid.Row="1" Height="100" Orientation="Horizontal" DataContext="{Binding ElementName=listView1,Path=SelectedItem}">
            <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

                <TextBlock Name="textBlock_ContactID" Text="ContactID:" />

                <TextBox Name="textBox_ContactID" MinWidth="100" Text="{Binding ContactID}" IsEnabled="True" />

            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

                <TextBlock Name="textBlock_FirstName" Text="FirstName:"  />

                <TextBox Name="textBox_FirstName" MinWidth="100" Text="{Binding FirstName}"/>

            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

                <TextBlock Name="textBlock_LastName" Text="LastName:" />

                <TextBox Name="textBox_LastName" MinWidth="100" Text="{Binding LastName}"/>

            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

                <TextBlock Name="textBlock_EmailAddress" Text="EmailAddress:" />

                <TextBox Name="textBox_EmailAddress" MinWidth="100" Text="{Binding EmailAddress}"/>

            </StackPanel>

        </WrapPanel>

        <StackPanel Orientation="Horizontal" Margin="5,2,5,2" Grid.Row="2" >
            <Button  HorizontalAlignment="Right"  Name="btnUpdata" Click="btnUpdata_Click"  >数据更新</Button>
            <Button  HorizontalAlignment="Center"  Name="btnAdd" Click="btnAdd_Click">添加</Button>
            <Button  HorizontalAlignment="Left"  Name="btnDell" Click="btnDell_Click">删除</Button>
            <Button  HorizontalAlignment="Left"  Name="button2" Width="57" Click="button2_Click">调用</Button>

        </StackPanel>


    </Grid>
</Window>



对应的Window1.xaml.cs代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using ;
using .Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace WPFTest
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            getData();

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            getData();
        }

        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           // this.textBox_ContactID.IsEnabled = false;

            textBox_ContactID.SetValue( TextBox.IsEnabledProperty, Convert.ToBoolean(false));
        }
        void getData() 
        { 
            //初始化数据连接.
            SqlConnection Myconn = this.createConn();

            //建立连接

            SqlDataAdapter sda = new SqlDataAdapter("select ContactID,FirstName,LastName,EmailAddress from dbo.person where ContactID<=100;", Myconn);
            //SqlCommandBuilder commBuilder = new SqlCommandBuilder(sda);
            //sda.UpdateCommand = commBuilder.GetUpdateCommand();

            DataTable dt =  new DataTable();

            //sda.AcceptChangesDuringUpdate = true;
            sda.Fill(dt);

            //与界面绑定
            this.listView1.ItemsSource = dt.DefaultView;
            Myconn.Close();

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Window win = new Window2();
            win.Show();
        }
        private SqlConnection createConn()
        {
            SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;database=Test;uid=login;password=login");
            //SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Test.MDF;Integrated Security=True;User Instance=True"); 
            return conn;
        }

        /*
         * 数据的更新
         * 
         * 
         */
        private void btnUpdata_Click(object sender, RoutedEventArgs e)
        {
            string id = this.textBox_ContactID.Text.ToString();
            string firstName = this.textBox_FirstName.Text.ToString();
            string lastName = this.textBox_LastName.Text.ToString();
            string eMail = this.textBox_EmailAddress.Text.ToString();
            SqlConnection Myconn = this.createConn();
            Myconn.Open();
            try 
            {
                SqlCommand cmd = new SqlCommand("update dbo.person set FirstName = '" + firstName + "',LastName='" + lastName + "',EmailAddress='" + eMail + "' where ContactID = '" + id + "'",Myconn);
                //SqlDataAdapter sda = new SqlDataAdapter("updata dbo.person set FirstName = '" + firstName + "',LastName='" + lastName + "',EmailAddress='" + eMail + "' where ContactID = '" +id+"'");
                cmd.ExecuteNonQuery();
                MessageBox.Show("更新成功!");

            }catch(Exception ex)
            {
                ex.ToString();
                MessageBox.Show("更新失败!");
            }
            finally 
            {
                Myconn.Close();
            }

        }

        /*
         * 数据的添加
         * 
         * 
         */
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string id = this.textBox_ContactID.Text.ToString();
            string firstName = this.textBox_FirstName.Text.ToString();
            string lastName = this.textBox_LastName.Text.ToString();
            string eMail = this.textBox_EmailAddress.Text.ToString();


            if (!this.IsHasData(id))
            {
                //不存在,进行数据添加
                SqlConnection Myconn = this.createConn();
                Myconn.Open();
                try
                {
                    string sql = "insert into dbo.person(ContactID,FirstName,LastName,EmailAddress) values('"+id+"','"+firstName+"','"+lastName+"','"+@eMail+"')";
                    SqlCommand cmd = new SqlCommand(sql,Myconn);
                    cmd.ExecuteNonQuery();

                    MessageBox.Show("数据添加成功!");

                    //不通过后台查询,直接反映到前台
                    //this.gridView1.Columns.Add(gvc);


                }
                catch (SqlException ex)
                {
                    ex.ToString();
                    MessageBox.Show("数据添加失败!");
                }
                finally 
                {
                    Myconn.Close();
                }

                // 通过后台查询反映到前台
                getData();
            }
            else 
            {
                //存在
                MessageBox.Show("数据ID已经存在!");
            }

        }

        /*
         * 判断是否存在数据
         * 
         * 
         */
        private bool IsHasData(string id) 
        {
            SqlConnection Myconn = this.createConn();
            Myconn.Open();
            try 
            {
                SqlCommand cmd = new SqlCommand("select count(*) from dbo.person where ContactID='" + id +"'",Myconn);
                int count = Convert.ToInt32(cmd.ExecuteScalar());
                if (count > 0)
                {
                    return true;
                }
                else 
                {
                    return false;
                }
            }
            catch(Exception ex)
            {
                ex.ToString();
                return false;
            }
            finally
            {
                Myconn.Close();

            }
        }
       /*
        * 数据的删除
        * 
        * 
        */
        private void btnDell_Click(object sender, RoutedEventArgs e)
        {
            string id = this.textBox_ContactID.Text.ToString();
            if(this.IsHasData(id))
            {
                //数据存在进行删除
                SqlConnection Myconn = this.createConn();
                Myconn.Open();
                try 
                {
                    string sql = "delete from dbo.person where ContactID ='"+ id+"'";
                    SqlCommand cmd = new SqlCommand(sql,Myconn);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("删除成功!");

                    //不通过后台查询,直接反映到前台
                    //this.gridView1.Columns.Add(gvc);

                }
                catch(SqlException ex)
                {
                    ex.ToString();
                }
                finally
                {
                    Myconn.Close();
                }

                // 通过后台查询反映到前台
                getData();
            }
        }
    }
}




注意:启动窗口设置为Window2


修改:App.xaml


<Application x:Class=""
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window2.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>




调试过程中的一个问题:


错误一:ExecuteNonQuery (或者ExecuteReader): Connection property has not been initialized



缺少参数:



下面是网上的摘抄:



using (SqlConnection conn = SqlHelper.GetSqlConnection()) 

{ 

 conn.Open (); 

 //Create table. 

 using (SqlCommand cmd = new SqlCommand (_cmdCreateTable)) 

 { 

 cmd.ExecuteNonQuery (); 

 } 

}



估计一下子还真不容易看出来,那就是


new SqlCommand (_cmdCreateTable)

缺少第二个参数:SqlConnection!




错误二:过程或函数 'xxx' 需要参数 '@xxx',但未提供该参数


这个可能原因就更多了,不过到后来我都排除了,最后发现是没有将SqlCommand对象的CommandType设为StoredProcedure! 真是囧了。不过还是挺奇怪的,毕竟没有设的话默认是Text,也就是说它会将存储过程名称当做SQL语句,那此时应该是它不需要参数而我给了参数(原本要传给存储过程的),所以这个错误信息实在是。。。



[img]http://dl.iteye.com/upload/attachment/201497/f741f941-30ae-3450-8971-4b269fd98d5c.bmp[/img]



[img]http://dl.iteye.com/upload/attachment/201499/c111f69d-8940-3c18-84a6-689f2011fb7b.bmp[/img]