Loading

DataGridView 控件操作大全 (内容居中显示,右键绑定菜单)

DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter '标题居中
DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter '内容居中

this.dataGridView1.AutoGenerateColumns = false;  //让它不自己产生多余的列

 // this.dataGridView1.AutoSizeColumnsModel = Fill   //列名占满容器

this.dataGridView1.AutoSizeColumnsModel = AllCells  //列名占满容器


 

        #region [DataGridView控件单元格点击事件,绑定右键菜单]
        private void dataGridView_Score_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //绑定右键菜单
                dataGridView_Score.SelectedRows[0].ContextMenuStrip = this.contextMenuStrip1;
            }
        }
        #endregion

 

DataGridView单元格内容显示格式化:代入

Dictionary<string,string>方法
  private void dataGridView_Score_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Dictionary<string,string> scoreStatus = GetScoreStatus();
            if (e.ColumnIndex == 7)
            {
                e.Value = scoreStatus[e.Value.ToString()];
                e.FormattingApplied = true;
            }
           
        }
  #region [设定ComboBox数据源]
        private Dictionary<string, string> GetScoreStatus()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"2", "全部"},
                {"1", "成功"},
                {"0", "失败"}
            };
            return dic;
        }
        #endregion

获取DataGridView选中数据,  返回对象:

 #region[获取DataGridView的选中行数据]
        /// <summary>
        /// 获取当前选中行的数据
        /// </summary>
        /// <returns>当前选中行数据</returns>
        private JudgeSetting GetSelectRowInfo()
        {
            DataGridViewRow selectRows = dataGridView_Judge.SelectedRows[0];
            JudgeSetting setting = new JudgeSetting();
            if (selectRows != null)
            {
                // 项目代码
                setting.Ksxmdm = Convert.ToInt32(selectRows.Cells["项目代码"].Value);
                // 项目名称
                setting.Gakfmc = Convert.ToString(selectRows.Cells["项目名称"].Value);
            }
            return setting;
        }
        #endregion


替换DataGridView头部显示,
  #region[替换DataTable头]
        /// <summary>
        /// 替换DataTable头
        /// </summary>
        /// <param name="dt">查询出的DataTable</param>
        /// <returns></returns>
        private DataTable ReplaceDataTableHead(DataTable dt)
        {
            dt.Columns[0].ColumnName = "项目代码";
            dt.Columns[1].ColumnName = "项目名称";
            dt.Columns[2].ColumnName = "扣分项目";
            return dt;
        }
        #endregion

        #region[DataTable样式调整]
        /// <summary>
        /// DataTable样式调整
        /// </summary>
        private void ChangeDataTableStyle()
        {
            // KEY列隐藏
            this.dataGridView_Judge.Columns[10].Visible = false;
            this.dataGridView_Judge.Columns[9].Visible = false;

            //this.dataGridView_Judge.Columns[0].Width = 80;
            //this.dataGridView_Judge.Columns[1].Width = 100;

            this.dataGridView_Judge.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }
        #endregion
绑定dataTable到DataGridView
   #region[绑定dataTable到DataGridView]
        /// <summary>
        /// 绑定dataTable到DataGridView
        /// </summary>
        /// <param name="dt">源DataTable</param>
        private void BindDataTble(DataTable dt)
        {
            if (toolStripComboBox1.Text != "全部")
            {
                DataRow[] rows = dt.Select(string.Format("GAKFMC = '{0}'", toolStripComboBox1.Text));
                DataTable table = dt.Clone();
                foreach(DataRow row in rows)
                {
                    table.Rows.Add(row.ItemArray);
                }
                dt = table;
            }

            // 修改DataTable头部
            dt = ReplaceDataTableHead(dt);
            // 绑定数据
            this.dataGridView_Judge.DataSource = dt;
            // 修改DataTable样式
            ChangeDataTableStyle();
            // 刷新读取的条数
            this.toolStripLabel4.Text = dt.Rows.Count.ToString();
        }
        #endregion
刷新DataGridView的绑定
  #region[刷新DataGridView的绑定]
        /// <summary>
        /// 刷新DataGridView的绑定
        /// </summary>
        /// <param name="sqlEnum">查询语句</param>
        private void RefreshBindTable(SqlStatusEnum sqlEnum)
        {
            try
            {
                DataTable dt = QueryData(sqlEnum, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    BindDataTble(dt);
                }
                else
                    MessageBox.Show("查询错误,或未查询到相关数据!");
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }

        }
        #endregion

 DataGridView控件绑定List<string>

 

        List<Student> strList = new List<Student>()
            {
                new Student(){StuId = 1, StuName = "张三"},
                new Student(){StuId = 2, StuName = "李四"},
                new Student(){StuId = 3, StuName = "王五"}
            };

            //查找出ID,并显示姓名,List<{m}>绑定到datagridview,可以把m去掉,.Select(m => new { m.StuName })这样展示就是StuName的列名
            var students = strList.Where(s =>s.StuId == 2).Select(m => new { m = m.StuName }).ToList();
        
            dataGridView1.DataSource = students;  //显示出以m为列名的数据,可以手动修改列名

 

将dataGridView选定的行转换为实体对象

    ContactModel model = dataGridView1.CurrentRow.DataBoundItem as ContactModel;

 


 

posted @ 2019-09-17 11:22  云辰  阅读(3042)  评论(0编辑  收藏  举报