即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

C#winform实现增删改查

编程语言 widenstage 20℃ 0评论
本文目录
[隐藏]

      上文介绍了pb实现增删改查,短短几十行代码就ok了,c#的winform相对麻烦一点,因为没有datawindow神器呀。

       数据库还是sqlserver,表的名字依然是table_test,字段dbid键值,xm1,xm2,xm3字符型。

1.首先使用vs建立一个windows窗口应用程序test

2.第二步,在form1上摆放控件



       和上文的pb的程序一样排版就可以,拖放一个datagridview,四个button,四个label,三个text,两个radiobutton还有两个groupbox。

3.第三步,编写一个处理数据库的类db.cs

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace test
{
    class db
    {
        public static string connectionstring = "server=localhost;database=db;uid=sa;pwd=password";

        public static SqlConnection OpenDB()
        {
            try
            {
                SqlConnection oConn = new SqlConnection(connectionstring);
                oConn.Open();

                return oConn;
            }
            catch
            {
                throw;
            }
        }

        public static void CloseDB(SqlConnection oConn)
        {
            try
            {
                oConn.Close();
            }
            catch
            {
                throw;
            }
        }

        public static DataSet Execute(string strCommandString)
        {
            try
            {
                SqlConnection oConn = OpenDB();

                DataSet oDataSet = new DataSet();
                SqlDataAdapter oDataAdapter = new SqlDataAdapter(strCommandString, oConn);
                oDataAdapter.Fill(oDataSet);

                CloseDB(oConn);

                return oDataSet;
            }
            catch
            {
                throw;
            }
        }

        public static int ExecuteNonQuery(string strCommandString)
        {
            int li_count = 0;
            SqlConnection oConn = null;
            SqlCommand oComm = null;
            try
            {
                oConn = new SqlConnection(connectionstring);
                oComm = new SqlCommand();
                oConn.Open();
                oComm.Connection = oConn;
                oComm.CommandText = strCommandString;
                li_count = oComm.ExecuteNonQuery();
                return li_count;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (oConn != null) oConn.Close();
            }
        }

        public static int ExecuteReid(string strCommandString)
        {
            int li_count = 0;
            SqlConnection oConn = null;
            SqlCommand oComm = null;
            try
            {
                oConn = new SqlConnection(connectionstring);
                oComm = new SqlCommand();
                oConn.Open();
                oComm.Connection = oConn;
                oComm.CommandText = strCommandString;
                li_count = Convert.ToInt32(oComm.ExecuteScalar().ToString());
                return li_count;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (oConn != null) oConn.Close();
            }
        }

    }
}

4.第四步:编写增删改查的程序

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

namespace test
{
    public partial class Form1 : Form
    {
        private string ls_dbid = "";

        public Form1()
        {
            InitializeComponent();
            get_db1("");
        }

        private int get_db1(string as_where)
        {
            string ls_sql = "select xm1,xm2,xm3,dbid from table_test " + as_where + " order by dbid";
            DataSet ds = new DataSet();
            try
            {
                ds = db.Execute(ls_sql);
            }
            catch
            {
                //数据库出错,相应的sql为getsql()
                MessageBox.Show("error of connect database");
            }

            dgv1.DataSource = ds.Tables[0].DefaultView;

            dgv1.Columns[0].HeaderText = "姓名";
            dgv1.Columns[1].HeaderText = "性别";
            dgv1.Columns[2].HeaderText = "电话";

            dgv1.Columns[0].Width = 200;
            dgv1.Columns[1].Width = 100;
            dgv1.Columns[2].Width = 400;
            dgv1.Columns[3].Visible = false;

            return ds.Tables[0].Rows.Count;

        }
        
        private void dgv1_MouseClick(object sender, MouseEventArgs e)
        {
            txt_xm1.Text = dgv1.CurrentRow.Cells[0].Value.ToString();
            string ls_xm2 = dgv1.CurrentRow.Cells[1].Value.ToString();
            if (ls_xm2.Equals("男"))
            {
                rb_1.Checked = true;
            }
            else
            { 
                rb_2.Checked = true;
            }
            txt_xm3.Text = dgv1.CurrentRow.Cells[2].Value.ToString();
            ls_dbid = dgv1.CurrentRow.Cells[3].Value.ToString();
    
        }

        private void dgv1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                                                e.RowBounds.Location.Y,
                                                dgv.RowHeadersWidth - 4,
                                                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                                  dgv.RowHeadersDefaultCellStyle.Font,
                                  rectangle,
                                  dgv.RowHeadersDefaultCellStyle.ForeColor,
                                  TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void bt_add_Click(object sender, EventArgs e)
        {
            txt_xm1.Text = "";
            rb_1.Checked = true;
            txt_xm3.Text = "";
            ls_dbid = "";
        }
        
        private void bt_save_Click(object sender, EventArgs e)
        {
            // *** 将信息更新到数据库           
            string ls_xm2 = "";
            if (rb_1.Checked)
            {
                ls_xm2 = "男";
            }
            else
            {
                ls_xm2 = "女";
            }
            if (ls_dbid == "")
            {
                string ls_sql = "INSERT INTO table_test ( xm1,xm2,xm3 )  VALUES (  @@xm1, @@xm2, @@xm3 ); SELECT dbid FROM table_test WHERE (dbid = @@IDENTITY)";
                ls_sql = ls_sql.Replace("@@xm1", "'" + txt_xm1.Text.ToString() + "'"); 
                ls_sql = ls_sql.Replace("@@xm2", "'" + ls_xm2 + "'");
                ls_sql = ls_sql.Replace("@@xm3", "'" + txt_xm3.Text.ToString() + "'");

                int li_ret1 = db.ExecuteReid(ls_sql);
                if (li_ret1 > 0)
                {
                    ls_dbid = li_ret1.ToString();
                }
                else
                {
                    MessageBox.Show("增加失败", "信息");
                    return;
                }
            }
            else
            {
                string ls_sql = "update table_test set xm1=@@xm1,xm2=@@xm2,xm3=@@xm3  where dbid = " + ls_dbid;
                ls_sql = ls_sql.Replace("@@xm1", "'" + txt_xm1.Text.ToString() + "'");       
                ls_sql = ls_sql.Replace("@@xm2", "'" + ls_xm2 + "'");
                ls_sql = ls_sql.Replace("@@xm3", "'" + txt_xm3.Text.ToString() + "'");
                db.ExecuteNonQuery(ls_sql);
            }
            get_db1("");
            MessageBox.Show("保存成功!", "信息");
        }

        private void bt_del_Click(object sender, EventArgs e)
        {
            if (ls_dbid == "")
            {
                MessageBox.Show("请选择要删除的记录");
            }
            else
            {
                string ls_sql = "delete from table_test where dbid=" + ls_dbid ;
                db.ExecuteNonQuery(ls_sql);
                get_db1("");
                MessageBox.Show("删除成功!", "信息");

            }
        }

        private void bt_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void txt_cx_TextChanged(object sender, EventArgs e)
        {
            string ls_where = "";
            if (this.Text.Equals(""))
            {
                ls_where = "";
            }
            else
            {
                ls_where = " where (xm1 like '%" + txt_cx.Text.ToString() + "%') or (xm2 like '%" + txt_cx.Text.ToString() + "%') or (xm3 like '%" + txt_cx.Text.ToString() + "%')";
            }
            get_db1(ls_where);
        }        

    }    
}

5.总结:

微软的工具,在windows平台上开发程序还是很高效的,短短几百行代码就把问题全部搞定了。


转载请注明:CodingBlog » C#winform实现增删改查

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情