首页 > 编程语言 >C#学习5(员工列表修改以及删除)

C#学习5(员工列表修改以及删除)

时间:2023-11-16 19:13:48浏览次数:31  
标签:MessageBox 删除 Show C# Text 列表 修改 new mySqlConnection

1.员工列表修改及添加

点击修改员工,弹出修改页面,修改窗口与添加窗口时同一个窗口,需要区分是添加还是修改。

设置一个变量用于判断当前窗口的功能,flag=0,则是添加;flag>0则是修改,修改传进来的flag就是需要修改的员工编号。

先找到datagridview的显示选择整行的模型

 

 

private void AddStaffForm_Load(object sender, EventArgs e)
        {
            //加载的时候判断添加还是修改
            if(flag == 0)
            {
                //添加功能
                button1.Text = "添加";
                //1.获取下拉列表
                setComboBox();

            }
            else
            {
                //修改功能
                button1.Text = "修改";
                //1.获取下拉列表
                setComboBox();
                //2.初始化窗体表数据
                setStaffById();

            }
        }
        /// <summary>
        /// 初始化修改窗口的员工信息
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void setStaffById()
        {
            MySqlConnection mySqlConnection = null;
            try
            {
                mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course");
                mySqlConnection.Open();
                string sql = string.Format("select * from staffInfo where sId = {0}", flag);
                MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection);
                MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
                if (mySqlDataReader.Read())
                {
                    sCardText.Text = mySqlDataReader["sCard"].ToString();
                    sNameText.Text = mySqlDataReader["sName"].ToString();
                    if (mySqlDataReader["sSex"].ToString() == "男")
                    {
                        nanBtn.Checked = true;
                    }
                    else
                    {
                        nvBtn.Checked = true;
                    }
                    ageCombo.Text = mySqlDataReader["sAge"].ToString();
                    sAddressText.Text = mySqlDataReader["sAddress"].ToString();
                    deptCombo.SelectedIndex = Convert.ToInt32(mySqlDataReader["deptId"]);
                    numericUpDown1.Value = Convert.ToDecimal(mySqlDataReader["sWages"]);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //throw;
            }
            finally
            {
                mySqlConnection.Close();
            }
            
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        private void setComboBox()
        {
            //年龄下拉框
            for(int i = 1; i < 121; i++)
            {
                ageCombo.Items.Add(i);
            }
            ageCombo.SelectedItem = 18;//设置默认值
            nanBtn.Checked = true;//默认性别男

            MySqlConnection mySqlConnection = null;
            try
            {
                mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course");
                mySqlConnection.Open();
                string sql = string.Format("select deptId,deptName from deptinfo");
                MySqlDataAdapter msda = new MySqlDataAdapter(sql, mySqlConnection);
                DataSet ds = new DataSet();


                //msda.Fill(ds);
                msda.Fill(ds, "depts");
                //添加请选择
                DataRow dr = ds.Tables["depts"].NewRow();
                dr[0] = "0";
                dr[1] = "请选择";
                ds.Tables["depts"].Rows.InsertAt(dr, 0);


                //显示值
                deptCombo.DisplayMember = "deptName";
                //隐藏值
                deptCombo.ValueMember = "deptId";

                deptCombo.DataSource = ds.Tables["depts"];
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //throw;
            }
            finally
            {
                mySqlConnection.Close();
            }
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //非空认证
            if (CheckInput())
            {
                //点击添加的时候,判断是添加还是修改员工
                if (flag == 0)
                {
                    //添加功能
                    insertStaff();
                }
                else
                {
                    //修改功能
                    updateStaff();

                }
            }
            
        }
        /// <summary>
        /// 非空认证
        /// </summary>
        private Boolean CheckInput()
        {
            if(sCardText.Text.Trim().Length == 0)
            {
                MessageBox.Show("员工工号不能为空");
                sCardText.Focus();
                return false;
            }
            if(sNameText.Text.Trim().Length == 0)
            {
                MessageBox.Show("员工姓名不能为空");
                sNameText.Focus();
                return false;
            }
            if(sAddressText.Text.Trim().Length == 0)
            {
                MessageBox.Show("员工地址不能为空");
                sAddressText.Focus();
                return false;
            }
            if(deptCombo.Text.Trim() == "请选择")
            {
                MessageBox.Show("请选择部门");
                deptCombo.Focus();
                return false;
            }
            //年龄和性别有默认值
            return true;
        }

        /// <summary>
        /// 添加员工信息
        /// </summary>
        private void insertStaff()
        {
            MySqlConnection mySqlConnection = null;
            try
            {
                mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course");
                mySqlConnection.Open();
                string sql = string.Format("insert into staffInfo(`sCard`,`sName`,`sSex`,`sAge`,`sAddress`,`deptId`,`sWages`)  values('{0}','{1}','{2}',{3},'{4}',{5},{6})"
                    , sCardText.Text.Trim()
                    , sNameText.Text.Trim()
                    , nanBtn.Checked == true ? "男" : "女"
                    , Convert.ToInt32(ageCombo.Text)
                    , sAddressText.Text.Trim()
                    , (int)deptCombo.SelectedValue//部门号是被隐藏了的
                    , numericUpDown1.Value
                    );
                MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection);
                int result = mySqlCommand.ExecuteNonQuery();
                if (result > 0)
                {
                    MessageBox.Show("添加成功");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //throw;
            }
            mySqlConnection.Close();
        }

        /// <summary>
        /// 修改员工信息
        /// </summary>
        private void updateStaff()
        {
            MySqlConnection mySqlConnection = null;
            try
            {
                mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course");
                mySqlConnection.Open();
                string sql = string.Format("update staffInfo set sCard='{0}',sName='{1}',sSex='{2}',sAge={3},sAddress='{4}',deptId={5},sWages={6} where sId={7}"
                    , sCardText.Text.Trim()
                    , sNameText.Text.Trim()
                    , nanBtn.Checked == true ? "男" : "女"
                    , Convert.ToInt32(ageCombo.Text)
                    , sAddressText.Text.Trim()
                    , (int)deptCombo.SelectedValue//部门号是被隐藏了的
                    , numericUpDown1.Value
                    , flag);
                MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection);
                int result = mySqlCommand.ExecuteNonQuery();
                if (result > 0)
                {
                    MessageBox.Show("修改成功");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("修改失败");
                    //this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //throw;
            }
            mySqlConnection.Close();
        }

 

2.修改完成后,关闭窗口,页面自动更新

 

 

3.删除员工操作

private void button3_Click(object sender, EventArgs e)
        {
            //删除操作
            DialogResult dialogResult = MessageBox.Show("确定要删除吗【" + dataGridView1.CurrentRow.Cells[2].Value + "】吗?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if(dialogResult == DialogResult.Yes)
            {
                MySqlConnection mySqlConnection = null;
                try
                {
                    mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course");
                    mySqlConnection.Open();
                    string sql = string.Format("delete from staffInfo where sId={0}"
                        , Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value));
                    MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection);
                    int result = mySqlCommand.ExecuteNonQuery();
                    if (result > 0)
                    {
                        MessageBox.Show("删除成功");
                        setDataGridView();//刷新
                    }
                    else
                    {
                        MessageBox.Show("删除失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    //throw;
                }
                finally
                {
                    mySqlConnection.Clone();
                }
            } 
            
        }

 

 

4.

 

标签:MessageBox,删除,Show,C#,Text,列表,修改,new,mySqlConnection
From: https://www.cnblogs.com/hmy22466/p/17837044.html

相关文章

  • 所见即所得的动画效果:Animate.css
    我们可以在集成Animate.css来改善界面的用户体验,省掉大量手写css动画的时间。官网:Animate.css使用1、安装依赖npminstallanimate.css--save2、引入依赖import'animate.css';3、在项目中使用在class类名上animate__animated是必须的,animate__flipInX为你应用的动画效......
  • react学习
    提升state?what?how?why?兄弟组件之间怎么共享state?onClick='fn()'会立即调用,传参使用onClick='()=>fn(id)'提前返回一些东西()的意义state不应在组件中改变state三部曲:1.定义它2.使用它3.更新它类似vue中的slot=childrenprop,传递jsxbill账单例子引发的问题?......
  • 【C++】【图像处理】形态学处理(腐蚀、膨胀)算法解析(以.raw格式的图像为基础进行图像处
    1voiderosion(BYTE*image,intw,inth,BYTE*outImg)2{3intrept;4//腐蚀5memcpy(outImg,image,sizeof(BYTE)*w*h);//将读取的图像赋值给outImg,方便进行腐蚀操作67inti,j,m,n;8BYTEflag;9for(rept=0;rept......
  • 记录一下oracle index skip引起 temp表空间暴涨问题
    1.indexskip这个东西发现有执行计划走他的时候一定要注意了,这玩意还会出发sort排序功能,所以会大量使用你的临时表空间  看到走了indexskip然后还有buffersort大概能猜到,这个走了比较差的索引了,然后继续查看CRS_P_GU_INSECACCT表上的索引发现有一个复合索引,就是执行计......
  • 【11月LeetCode组队打卡】Task1--HashTable
    在准备CSP,借这次组队打卡的机会好好复习一下cpp的各种基操(微操,和基础的数据结构217.存在重复元素vector向量的用法有点忘了,先简单回顾一下(其实是好久没写cpp了(安详.jpg输入与输出//未知数组元素个数vector<int>hash;intx;while(cin>>x){hash......
  • JdbcTemplate中如何进行存储过程调用
    JdbcTemplate调用存储过程的主要有三种方发(精)一、jdbcTemplate.call()定义如下:Map<String,Object>call(CallableStatementCreatorcsc,List<SqlParameter>declaredParameters)throwsDataAccessException;第一个参数是创建调用存储过程的方法的参数,第二个参数是返回结果的Map......
  • element中select组件加入滚动分页及模糊查询
    element中select组件加入滚动分页及模糊查询1.directive.js-自定义vue指令importVuefrom'vue'exportdefault()=>{Vue.directive('loadMore',{bind(el,binding){//如上图,我通过v-if来控制了两个select框,当没有binding.arg这个参数时,我只能监听到企......
  • static 关键字
    title:statickeywordlayout:pagecategories:cppstatickeyword编译器信息:╰─>$clang++--versionAppleclangversion15.0.0(clang-1500.0.40.1)Target:arm64-apple-darwin23.1.0Threadmodel:posixInstalledDir:/Applications/Xcode.app/Contents/Develo......
  • 反编译C#的dll文件并修改,再重新生成dll
    1、把dll文件导入到ildasm工具中,ildasm是由微软提供的.net程序反编译工具,位于“C:\ProgramFiles\MicrosoftSDKs\Windows\v6.0A\bin” 2、在ildasm中File->dump,把dll文件转储为*.il文件存到某个指定文件夹里,得到*.il和*.res两个文件,有时也会有*.resource文件 3、打开得到的......
  • 客户的一个紧急bug,我用了两种方式进行 C# 反编译修改源码
    一:背景1.讲故事周五下午运营反馈了一个紧急bug,说客户那边一个信息列表打不开,急需解决,附带的日志文件也发过来了,看了下日志大概是这样的:日期:2020-11-1312:25:45,923线程ID:[3924]日志级别:INFO 错误类:xxxproperty:[(null)]-错误描述:应用程序出现了未捕获的异常,Message......