您的位置:首页 > 编程语言 > C#

C#拒绝添加重复信息与关闭提示

2015-07-21 15:29 691 查看
一个简单的WindowsFormsApplication程序,向Listview中添加数据,重复或空白时会报警,关闭时会提示是否关闭







using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            if (textBox1.Text == "") //判断文本框中是否为空

            {

                button3.Text = "商品名称不能为空";

                button3.ForeColor = Color.Red;

                textBox1.Focus();

            }

            else

            {

                if (listBox1.Items.Count > 0)

                {

                    for (int i = 0; i < listBox1.Items.Count; i++)
//遍历文本中的数据

                    {

                        if (listBox1.Items[i].ToString() == textBox1.Text)
//判断是否与已有的文本重复

                        {

                            button3.Text = "商品已存在";

                            button3.ForeColor = Color.Red;

                            textBox1.Clear();

                            textBox1.Focus();

                            

                        }

                    }

                    //listBox1.Items.Add(textBox1.Text);

                    //textBox1.Clear();

                }

                listBox1.Items.Add(textBox1.Text);
//若没有重复,则想ListView中添加文本

                textBox1.Clear(); //清空文本框

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            listBox1.Items.Clear();

        }

        //private void button4_Click(object sender, EventArgs e)

        //{

        //}

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            DialogResult dr;

            dr = MessageBox.Show("确认退出吗?","确认谈话框",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button3);

            if (dr==DialogResult.Yes)

            {

            

            }

            else

            {

                e.Cancel = true;            
            }

/*窗口正要关闭但是还没关闭之前会触发formclosing事件,该事件中的参数FormClosingEventArgs中包含Cancel属性,如果设置该属性为true,窗口将不会关闭。*/

        }

    }
}

完整文件下载地址:http://download.csdn.net/detail/qq_28597703/8919627
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: