C#操作DataGridview

复制代码
DataTable dt = new DataTable();
            //新建列
            DataColumn col1 = new DataColumn("设备名", typeof(string));
            DataColumn col2 = new DataColumn("管理员", typeof(string));
            DataColumn col3 = new DataColumn("设备ID", typeof(string));
            DataColumn col4 = new DataColumn("所属权限", typeof(string));
            DataColumn col5 = new DataColumn("状态", typeof(string));
            DataColumn col6 = new DataColumn("购买时间", typeof(string));
            DataColumn col7 = new DataColumn("最新维护时间", typeof(string));
            DataColumn col8 = new DataColumn("设备管理员ID", typeof(string));
            //添加列
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);
            dt.Columns.Add(col5);
            dt.Columns.Add(col6);
            dt.Columns.Add(col7);
            dt.Columns.Add(col8);
            //新建行
            DataRow row1 = dt.NewRow();
            //行赋值
            row1["设备名"] = "打印机";
            row1["管理员"] = "李居明";
            row1["设备ID"] = "JFKSJFKSDFJK151";
            row1["所属权限"] = "普通用户";
            row1["状态"] = "在库";
            row1["购买时间"] = "2012-03-20";
            row1["最新维护时间"] = "2012-03-27";
            row1["设备管理员ID"] = "";
            //添加行
            dt.Rows.Add(row1);
            //数据绑定
            this.dataGrid1.DataSource = dt;
            //设置属性
            DataGridTableStyle tablestyle = new DataGridTableStyle();
            this.dataGrid1.TableStyles.Add(tablestyle);
            dataGrid1.TableStyles[0].GridColumnStyles[0].Width = 75;
            dataGrid1.TableStyles[0].GridColumnStyles[1].Width = 75;
            dataGrid1.TableStyles[0].GridColumnStyles[2].Width = 75;
            dataGrid1.TableStyles[0].GridColumnStyles[3].Width = 75;
            dataGrid1.TableStyles[0].GridColumnStyles[4].Width = 75;
            dataGrid1.TableStyles[0].GridColumnStyles[5].Width = 120;
            dataGrid1.TableStyles[0].GridColumnStyles[6].Width = 120;
            dataGrid1.TableStyles[0].GridColumnStyles[6].Width = 120;
复制代码

 2.改变单元格颜色

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e){
            if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
            {
                DataGridViewCell aa = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                aa.Style.ForeColor = Color.Red;
                aa.Style.BackColor = Color.LightGreen;
            }
}

3.动态改变单元格颜色(需要用到绑定语法以及依赖属性)

1
-------------------待完成

 

posted @   懒树懒  阅读(302)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示