码道至简

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1、设置行高 列宽 设置内容格式 验证输入单元格的内容是否正确 

  private void Form1_Load(object sender, EventArgs e)
        {
            //设置网格颜色
            dataGridView1.GridColor = Color.Red;
            List<Student> stu = new List<Student>();
            Student s1=new Student();       
            s1.Name="小明";
            s1.age=23;
            stu.Add(s1);
            Student s2 = new Student();
            s2.Name = "老张";
            s2.age = 21;
            stu.Add(s2);
            Student s11 = new Student();
            s11.Name = "小李";
            s11.age = 30;
            stu.Add(s11);
            Student s22 = new Student();
            s22.Name = "云峰";
            s22.age = 20;
            stu.Add(s22);
            //绑定数据源
            dataGridView1.DataSource=stu;
            //设置网格中字体的样式
            dataGridView1.DefaultCellStyle.Font = new Font("黑体", 15);
            //设置列宽
            dataGridView1.Columns[1].Width = 170;
            //设置内容格式
            dataGridView1.DefaultCellStyle.Format = "c";
            //设置行高
            dataGridView1.Rows[0].Height = 70;
            //设置对齐方式
            dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
           //是否换行显示过长的内容
            dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True ;
        }
        //单元格验证时事件  可以验证指定列输入的内容是否符合要求
        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 1) //验指定列
            {
                int result = 0;
                if (!int.TryParse(e.FormattedValue.ToString(), out result))
                {
                    dataGridView1.Rows[e.RowIndex].ErrorText = "内容必须为整数类型"; //提示错误信息
                    e.Cancel = true;
                }
            }
        }
    }
    class Student
    {
        public string Name { get; set; }
        public int age { get; set; }
    }

 

posted on 2017-12-28 15:34  码道至简  阅读(763)  评论(0编辑  收藏  举报