简单的数据绑定和ADO.NET的应用

高手莫取笑,菜鸟可学习!我也是菜鸟来的,O(∩_∩)O~呵呵~~,大家共同探讨,共同学习,有什么好的学习方式和经验可提出来,大家共同进步!

本实例是在VS2005建立三个FORM窗体,代码如下:

1

 

From1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

 

namespace sy2_2

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        //修改密码处理事件

 

        private void button1_Click(object sender, EventArgs e)

        {

            SqlConnection conData = new SqlConnection();

            conData.ConnectionString = "server=localhost;Trusted_Connection=yes;Database=Car_DB";

            string str=string .Format ("select count(*) from userLogin where userID='{0}' and userPwd='{1}'",textBox1 .Text,textBox2.Text);

            SqlCommand cmd = new SqlCommand(str,conData);

            conData.Open();

            int i= (int)cmd.ExecuteScalar();

            if (textBox3.Text == textBox4.Text)

            {

                if (i == 1)

                {

                    string updateStr = string.Format("update userLogin set userPwd='{2}' where userID='{0}' and userPwd='{1}'", textBox1.Text, textBox2.Text, textBox3.Text);

                    cmd.CommandText = updateStr;

                    cmd.ExecuteNonQuery();

                    MessageBox.Show("密码修改成功!""提示"MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                else

                {

                    MessageBox.Show("旧密码或用户输入有误,请重新输入!""提示"MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

            else

            {

                MessageBox.Show("新密码和确认密码不一致,请重新输入!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

            }

            conData.Close();

        }

        //退出按钮事件

 

        private void button2_Click(object sender, EventArgs e)

        {

            Application.Exit();

        }

 

    }

}

 

2

Form2.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

 

namespace sy2_2

{

    public partial class Form2 : Form

    {

        public Form2()

        {

            InitializeComponent();

        }

 

        DataSet ds1, ds2;

        BindingManagerBase bmb1;

        SqlDBHelper sqlDB;

        //控件的简单绑定,用法都是一样的,只不过是重复的操作

        private void Form2_Load(object sender, EventArgs e)

        {

            sqlDB = new SqlDBHelper();

            string selectStr1 = "select * from user_inf";

            ds1 = sqlDB.getDataSet(selectStr1);

            string selectStr2 = "select * from Car_information";

            ds2 = sqlDB.getDataSet(selectStr2);

 

            Binding userID = new Binding("text", ds1, " .userID");

            userNameTxtBox.DataBindings.Add(userID);

            Binding userName = new Binding("text", ds1, " .userName");

            nameTxtBox.DataBindings.Add(userName);

            Binding userSex = new Binding("text", ds1, " .userSex");

            genderTxtBox.DataBindings.Add(userSex);

            Binding userAge = new Binding("text", ds1, " .userAge");

            birthDateTimePicker.DataBindings.Add(userAge);

            Binding userPost = new Binding("text", ds1, " .userPost");

            positionTxtBox.DataBindings.Add(userPost);

            Binding userIdCard = new Binding("text", ds1, " .userIdCard");

            idTxtBox.DataBindings.Add(userIdCard);

            Binding userPhone = new Binding("text", ds1, " .userPhone");

            telephoneTxtBox.DataBindings.Add(userPhone);

            Binding userEmail = new Binding("text", ds1, " .userEmail");

            eMailTxtBox.DataBindings.Add(userEmail);

            Binding userAdd = new Binding("text", ds1, " .userAdd");

            addressTxtBox.DataBindings.Add(userAdd);

 

            //CarID,品牌,车型,价格,排量,颜色,生产日期,产地,车系,登记日期,出售日期,备注,CarStatus

            Binding carID = new Binding("text", ds2, " .CarID");

            carIdTxtBox.DataBindings.Add(carID);

            Binding brand = new Binding("text", ds2, " .品牌");

            brandTxtBox.DataBindings.Add(brand);

            Binding type = new Binding("text", ds2, " .车型");

            carTypeTxtBox.DataBindings.Add(type);

            Binding price = new Binding("text", ds2, " .价格");

            priceTxtBox.DataBindings.Add(price);

            Binding displacement = new Binding("text", ds2, " .排量");

            displacementTxtBox.DataBindings.Add(displacement);

            Binding color = new Binding("text", ds2, " .颜色");

            colorTxtBox.DataBindings.Add(color);

            Binding proDateTime = new Binding("text", ds2, " .生产日期");

            produceDateTimePicker.DataBindings.Add(proDateTime);

            Binding proAddress = new Binding("text", ds2, " .产地");

            produceAddTxtBox.DataBindings.Add(proAddress);

            Binding carDepartment = new Binding("text", ds2, " .车系");

            carDepartmentTxtBox.DataBindings.Add(carDepartment);

            Binding register = new Binding("text", ds2, " .登记日期");

            registerDateTimePicker.DataBindings.Add(register);

            Binding saleDateTime = new Binding("text", ds2, " .出售日期");

            saleDateTimePicker.DataBindings.Add(saleDateTime);

            Binding carComtent = new Binding("text", ds2, " .备注");

            comtentTxtBox.DataBindings.Add(carComtent);

            

 

 

            sqlDB.allBind(ds1, dataGridView1, bindingSource1, bindingNavigator1);

            bmb1 = BindingContext[ds1, " "];

        }

        //切换面板时,视图的绑定对象改变;也可用几个视图,然后设置相对的显示和隐藏

 

        private void informationCtl_SelectedIndexChanged(object sender, EventArgs e)

        {

            switch (informationCtl.SelectedTab.Name)

            {

                case "empTabPage":

                    {

                        sqlDB.allBind(ds1, dataGridView1, bindingSource1, bindingNavigator1);

                        bmb1 = BindingContext[ds1, " "];

                        break;

                    }

                case "carTabPage":

                    {

                        sqlDB.allBind(ds2, dataGridView1, bindingSource1, bindingNavigator1);

                        bmb1 = BindingContext[ds2, " "];

                        break;

                    }

                case "cusTabPage":

                    {

                        break;

                    }

            }

        }

 

        private void firstBtn_Click(object sender, EventArgs e)

        {

            bmb1.Position = 0;

        }

 

        private void previousBtn_Click(object sender, EventArgs e)

        {

            if (bmb1.Position > 0)

            {

                bmb1.Position--;

            }

            else

            {

                MessageBox.Show("这已经是第一条记录了!""提示");

            }

        }

 

        private void nextBtn_Click(object sender, EventArgs e)

        {

            if (bmb1.Position < bmb1.Count - 1)

            {

                bmb1.Position++;

            }

            else

            {

                MessageBox.Show("这已经是最后一条记录了!""提示");

            }

        }

 

        private void lastBtn_Click(object sender, EventArgs e)

        {

            bmb1.Position = bmb1.Count - 1;

        }

 

        private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)

        {

            bmb1.Position = 0;

        }

 

        private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)

        {

            bmb1.Position--;

        }

 

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)

        {

            bmb1.Position++;

        }

 

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)

        {

            bmb1.Position = bmb1.Count - 1;

        }

       //保存按钮事件

 

        private void SaveToolStripButton_Click(object sender, EventArgs e)

        {

            try

            {

                sqlDB.con.Open();

                switch (informationCtl.SelectedTab.Name)

                {

                    case "empTabPage":

                        {

                            sqlDB.da = new SqlDataAdapter ("select * from user_inf",sqlDB .con);

                            SqlCommandBuilder cmdBD1 = new SqlCommandBuilder(sqlDB.da);

                            sqlDB.da.Update(ds1, " ");

                            MessageBox.Show("更新成功!");

                            break;

                        }

                    case "carTabPage":

                        {

                            sqlDB.da= new SqlDataAdapter ("select * from Car_information",sqlDB .con);

                            SqlCommandBuilder cmdBD2 = new SqlCommandBuilder(sqlDB.da);

                            sqlDB.da.Update(ds2, " ");

                            MessageBox.Show("更新成功!");

                            break;

                        }

                    case "cusTabPage":

                        {

                            break;

                        }

                }

            }

            catch (Exception em)

            {

                MessageBox.Show(em.Message);

            }

            finally

            {

                sqlDB.con.Close();

            }

        }

    }

        

}

3

MainFrm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

 

namespace sy2_2

{

    public partial class MainFrm : Form

    {

        public MainFrm()

        {

            InitializeComponent();

        }

        private int i = 3;

        private void MainFrm_Load(object sender, EventArgs e)

        {

            string[] userType = new string[] {"超级管理员","管理员","普通用户"};

            userTypeCmbBox.DataSource = userType;

        }

        //判断登录用户级别,并做出相应的处理;例如普通用户无法查看

 

        private void sureBtn_Click(object sender, EventArgs e)

        {

            SqlConnection con = new SqlConnection("server=.;database=Car_DB;Trusted_Connection=true;");

            SqlCommand cmd = new SqlCommand();

            string SelectStr = string.Format("select count(*) from userLogin where userID='{0}' and userPwd='{1}' and Legalpower='{2}'"

            userTxtBox.Text.TrimStart(), PwdTxtBox.Text.TrimStart(),userTypeCmbBox .SelectedItem);

            cmd.CommandText =SelectStr;

            cmd.Connection = con;

            con.Open();

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

            if (i > 0)

            {

                if (result == 1)

                {

                    MessageBox.Show("欢迎" + userTypeCmbBox.Text + "登录!""欢迎"MessageBoxButtons.OK, MessageBoxIcon.Information);

                    switch (userTypeCmbBox.Text)

                    {

                        case "超级管理员":

                        case "管理员":

                            Form2 frm2 = new Form2();

                            frm2.Show();

                            this.Hide();

                            break;

                        case "普通用户":

                            MessageBox.Show("普通用户界面还未创建,请获取更高的权限!""没有权限查看");

                            break;

                    }

                }

                else

                {

                    MessageBox.Show("用户名和密码输入有误或选择用户类型不正确!""登录失败"MessageBoxButtons.OK, MessageBoxIcon.Information);

                    PwdTxtBox.Clear();

                    i--;

                }

            }

            else

            {

                MessageBox.Show("登录次数超过限制次数,系统自动退出!","系统退出",MessageBoxButtons.OK,MessageBoxIcon.Warning);

                Application.Exit();

            }

        }

        //退出按钮事件

 

        private void cancelBtn_Click(object sender, EventArgs e)

        {

            Application.Exit();

        }

       //修改密码按钮事件

 

        private void modifyPwdBtn_Click(object sender, EventArgs e)

        {

            Form1 frm1 = new Form1();

            frm1.Show();

        }

    }

}

 

引用的DBHelper.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OleDb;

using System.Data .SqlClient;

using System.Data;

using System.Windows.Forms;

 

 

namespace sy2_2

{

    class AccessDBHelper

    {

       //连接Access的groupattachment1数据库语句

        private static string conStr1 = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=groupattachment1.mdb;";

        public static OleDbConnection conData1 = new OleDbConnection(conStr1);

 

        public DataSet getDataSet(string str)

        {

            conData1.Open();

            OleDbDataAdapter da1 = new OleDbDataAdapter(str,conData1);

            DataSet ds1 = new DataSet();

            da1.Fill(ds1," ");

            conData1.Close();

            return ds1;

        }

        //判断更新是否成功

 

        public Boolean updateSql(string sql)

        {

            OleDbCommand cmd1 = new OleDbCommand(sql,conData1);

            try

            {

                conData1.Open();

                cmd1.ExecuteNonQuery();

                return true;

            }

            catch (Exception e)

            {

                MessageBox.Show(e.Message ,"提示",MessageBoxButtons .OK,MessageBoxIcon.Information);

                return false;

            }

            finally

            {

                conData1.Close();

            }

        }

    }

    class SqlDBHelper

    {

       //连接数据库SQL的Car_DB数据库语句

        private static string conStr = "Data source=localhost;Initial Catalog=Car_DB;Integrated Security=SSPI";

        public SqlConnection con = new SqlConnection(conStr);

        public SqlDataAdapter da;

        //通过sql语句得到数据集对象

        public DataSet getDataSet(string str)

        {

            da = new SqlDataAdapter(str,con);

            con.Open();

            DataSet ds = new DataSet();

            //SqlCommandBuilder cmdBd = new SqlCommandBuilder(da);

            da.Fill(ds," ");

            con.Close();

            return ds;

        }

       //判断更新是否成功  

 

        public Boolean updateSql(string sql)

        {

            SqlCommand cmd = new SqlCommand(sql,con);

            try

            {

                con.Open();

                cmd.ExecuteNonQuery();

                return true;

            }

            catch (Exception e)

            {

                MessageBox.Show(e.Message, "提示"MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;

            }

            finally

            {

                con.Close();

            }

        }

        //绑定数据源    

        internal void allBind(DataSet ds, DataGridView dgv, BindingSource bs, BindingNavigator bn)

        {

            BindingSource bind = new BindingSource();

            bind.DataSource =ds.Tables [0];

            dgv.DataSource = bind;

            bs.DataSource = bind;

            bn.BindingSource =bind;

        }

    }

}

 

posted @ 2009-05-31 15:20  KenmuHuang  阅读(357)  评论(0编辑  收藏  举报
如果您看完本篇博文,觉得对您有所收获,请点击右下角的 [推荐]
如果您想转载,请注明出处(原创内容,请尊重个人劳动成果)
如果您有任何意见或建议,欢迎留言
感谢您的阅读,敬请关注我的后续博客文章