欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

winform 杂记

程序员文章站 2022-06-08 22:17:03
...

一、窗体显示为对话框

效果:

winform 杂记

代码:

        public Form7()
        {
            InitializeComponent();

            LoginForm loginform = new LoginForm();
            DialogResult dg = loginform.ShowDialog();
            if (dg == DialogResult.OK)
            {
                // 初始化代码
            }
            else
            {
                Environment.Exit(0);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

二、DataGridView 设置标头、绑定数据、下拉列表事件

            // 方法一:代码添加列
            //dataGridView1.ColumnCount = 1;// 列数
            //dataGridView1.Columns[0].Name = "第1列";
            //dataGridView1.Columns[0].CellTemplate=new DataGridViewTextBoxCell();
            //dataGridView1.Columns[0].ReadOnly = false;
            //dataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
            //dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            //dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.DeepSkyBlue;

            // 方法二: 代码添加列
            dataGridView1.AutoGenerateColumns = false;
            DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
            col1.HeaderText = "第1列";
            col1.ReadOnly = false;
            // 不排序
            col1.SortMode = DataGridViewColumnSortMode.NotSortable;
            //自动宽度
            col1.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            // 列表背景颜色
            col1.HeaderCell.Style.BackColor = Color.DeepSkyBlue;
            dataGridView1.Columns.Add(col1);


            DataGridViewComboBoxColumn Col2 = new DataGridViewComboBoxColumn();
            Col2.HeaderText = "第二列";
            Col2.Width = 200;
            Col2.Items.AddRange(new object[] { "", "aaaaaaa", "bbbb", "ccccc" });
            dataGridView1.Columns.Add(Col2);

            //列冻结
            dataGridView1.Columns[0].Frozen = true;
            // 不显示头列
            dataGridView1.RowHeadersVisible = false;
            for (int i = 0; i < 20; i++)
            {
                int index = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].Cells[0].Value = index + 1;
            }

            // 设置下拉列表选中
            dataGridView1.Rows[0].Cells[1].Value = "bbbb";
        ComboBox CboItemName;
        TextBox control;
        DataGridViewCellStyle dataGridViewCellStyle;
        // 下拉列表,或文件框发生改变
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //判断相应的列
            if (dataGridView1.CurrentCell.ColumnIndex == 1 && dataGridView1.CurrentCell.RowIndex != -1)
            {
                CboItemName = e.Control as ComboBox;
                //每次注册事件的时候先移除事件,避免不断被递归调用
                CboItemName.SelectedIndexChanged -= new EventHandler(CboItemName_SelectedIndexChanged);
                CboItemName.SelectedIndexChanged += new EventHandler(CboItemName_SelectedIndexChanged);
            }

            //只对TextBox类型的单元格进行验证
            //if (dataGridView1.CurrentCell.ColumnIndex != 21 && e.Control.GetType().BaseType.Name == "TextBox")
            //{
            //    control = new TextBox();
            //    control = (TextBox)e.Control;
            //    control.KeyPress -= new KeyPressEventHandler(control_KeyPress);
            //    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
            //}
        }

        private void CboItemName_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 样式
            dataGridViewCellStyle = new DataGridViewCellStyle();
            dataGridViewCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));

            dataGridViewSytle1("");
        }

        private void dataGridViewSytle1(string style)
        {
            switch (style)
            {
                case "":
                    dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value = "";
                    dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Style = dataGridViewCellStyle;
                    dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value = "";
                    dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Style = null;
                break;
            }
        }

三、导出 Excel

        public static void ExportExcel(string fileName, System.Data.DataTable dt)
        {
            设置导出文件路径
            //string path = HttpContext.Current.Server.MapPath("Export/");

            设置新建文件路径及名称
            //string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";

            try
            {
                string saveFileName = "";
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消
                //创建文件
                FileStream file = new FileStream(saveFileName, FileMode.CreateNew, FileAccess.Write);

                //以指定的字符编码向指定的流写入字符
                StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));

                StringBuilder strbu = new StringBuilder();

                //写入标题
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strbu.Append(dt.Columns[i].ColumnName.ToString() + "\t");
                }
                //加入换行字符串
                strbu.Append(Environment.NewLine);

                //写入内容
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        strbu.Append(dt.Rows[i][j].ToString() + "\t");
                    }
                    strbu.Append(Environment.NewLine);
                }

                sw.Write(strbu.ToString());
                sw.Flush();
                file.Flush();

                sw.Close();
                sw.Dispose();

                file.Close();
                file.Dispose();
                MessageBox.Show("成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件已存在!");

            }

        }

四、串口、网口

public static SerialPort HVcomm = new SerialPort();

            try
            {
                HVcomm.PortName = "COM1";
                HVcomm.DataBits = 8;//数据位
                HVcomm.BaudRate = 9600;//波特率
                HVcomm.StopBits = StopBits.One;//停止位
                HVcomm.Parity = Parity.None;//校验位
                if (HVcomm.IsOpen == true)//如果打开状态,则先关闭一下
                {
                    HVcomm.Close();
                }
                HVcomm.Open();
                
                // 发送数据看说明书


                

            }
            catch (Exception ex)
            {
               
            }

        /// <summary>
        /// 套接字(写)
        /// </summary>
        public static Socket WriteSock;

            try
            {
                WriteSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint serverip = new IPEndPoint(IPAddress.Parse("192.168.50.106"), int.Parse("12345"));
                WriteSock.Connect(serverip);
            }
            catch (Exception ex)
            {
                //
            }

            // 发送数据
            string PostString = "0A0B00000300A200000B0A";
            if (WriteSock.Connected == true)
            {
                try
                {
                    WriteSock.Send(HexStrTobyte(PostString));

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("没连接到PC机");
            }
        public static byte[] HexStrTobyte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
            return returnBytes;
        }

 

相关标签: Winforms