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

c#操控 DataGridView 常用用法日志

2013-01-14 14:30 246 查看
DataGridView 是个常用控件,不过用法不熟练,每次都要查阅相关资料。还是总结一下备次查阅

1 把DataGridView 拖到指定的位置,并Edit Columns。成下图所示界面



2 需求:实现导航功能

双击增加“bindingNavigatorBuildings”导航控件和“bindingSourceBuildings”控件

设置bindingNavigatorBuildings.BindingSource=bindingSourceBuildings

设置dataGridViewBuildings.DataSource=bindingSourceBuildings

3 需求:每条记录中自动生成默认值。

思路:在DataGridView 的DefaultValuesNeed中写如下代码:

private void dataGridViewBuildings_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            // 设定单元格的默认值
            e.Row.Cells[0].Value = "默认建筑";
            e.Row.Cells[1].Value = 1;
            e.Row.Cells[2].Value = 1;
            e.Row.Cells[3].Value = 1;
            e.Row.Cells[4].Value = 1;
            e.Row.Cells[5].Value = true;
            e.Row.Cells[6].Value = false;
            e.Row.Cells[7].Value = false;
            e.Row.Cells[8].Value = true;

        }


4 需求:实现DataGridView 每行新增自动出现索引,索引从1开始。

在DataGridView 的RowPostPaint事件下添加如下代码:

private void dataGridViewBuildings_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

{
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,dataGridViewBuildings.RowHeadersWidth - 4,   e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dataGridViewBuildings.RowHeadersDefaultCellStyle.Font, rectangle, dataGridViewBuildings.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


5 需求:从DataGridView 中获取用户输入的内容



如上图所示设置checkbox列的FalseValue和TrueValue。使用下示代码来获取用户信息。

/// <summary>
        /// //dwg中信息赋值到buildings中
        /// </summary>
        private bool GetBuildingsSimpleInfoFromDgw()
        {
            //dwg中信息赋值到buildings中
            buildings = new List<BuildingsSimpleInfomation>();
            int sumCount =dataGridViewBuildings.Rows.Count-1;
            if (sumCount > 0)
            {
                for (int i = 0; i < sumCount; i++)
                {
                    BuildingsSimpleInfomation bs = new BuildingsSimpleInfomation();
                    bs.m_ID = (i + 1).ToString();
                    bs.m_sName = dataGridViewBuildings.Rows[i].Cells[0].Value.ToString();
                    bs.m_nEl = Convert.ToInt32(dataGridViewBuildings.Rows[i].Cells[1].Value);
                    bs.m_nCl = Convert.ToInt32(dataGridViewBuildings.Rows[i].Cells[2].Value);
                    bs.m_nOutd = Convert.ToInt32(dataGridViewBuildings.Rows[i].Cells[3].Value);
                    bs.m_nInd = Convert.ToInt32(dataGridViewBuildings.Rows[i].Cells[4].Value);
                    bs.m_bIsR1 = Convert.ToBoolean(dataGridViewBuildings.Rows[i].Cells[5].Value);
                    bs.m_bIsR2 = Convert.ToBoolean(dataGridViewBuildings.Rows[i].Cells[6].Value);
                    bs.m_bIsR3 = Convert.ToBoolean(dataGridViewBuildings.Rows[i].Cells[7].Value);
                    bs.m_bIsR4 = Convert.ToBoolean(dataGridViewBuildings.Rows[i].Cells[8].Value);
                    buildings.Add(bs);
                }
                return true;
            }
            else
            {
                MessageBox.Show("请填写建筑相关信息。");
                return false;
            }
        }


6 如需代码给DataGridView 写入内容,使用DataTable

/// <summary>
        /// 在dataGridViewProjects中显示指定项目信息
        /// </summary>
        /// <param name="_projectsList"></param>
        private void ShowDgv(List<ProjectsOriginalParam_Memory> _projectsList)
        {
            //todo 把项目信息放入dgv
            DataTable dt = new DataTable();
            dt.Columns.Add("项目ID");
            dt.Columns.Add("项目名称");
            dt.Columns.Add("项目所在地");
            dt.Columns.Add("起始日期");
            dt.Columns.Add("完成日期");
            foreach (ProjectsOriginalParam_Memory _project in _projectsList)
            {
                DataRow dr = dt.NewRow();
                dr["项目ID"] = _project.ProjectsID;
                dr["项目名称"] = _project.ProjectsName;
                dr["项目所在地"] = _project.ProjectsArea;
                dr["起始日期"] = _project.ProjectsStartDateTime;
                dr["完成日期"] = _project.ProjectsEndDateTime;
                dt.Rows.Add(dr);
                //this.AddProjects(_project.ProjectsID, _project.ProjectsName, _project.ProjectsArea, _project.ProjectsStartDateTime, _project.ProjectsEndDateTime);           
            }
            dataGridViewProjects.DataSource = dt;
        }


7 整体移动某行

设计器中只是添加了按钮和datagridview,把datagridview的selectionMode设置为FullRowSelect

private DataTable dt;//定义一个datatable,作为datagridview的数据源

private void toolStripButtonUp_Click(object sender, EventArgs e)
        {
            //move up
            try
            {
                if (dt != null)
                {
                    dt = (DataTable)dataGridViewBuildings.DataSource;
                    int index = dataGridViewBuildings.SelectedRows[0].Index;

                    if (dataGridViewBuildings.CurrentRow.Index <= 0)
                    {
                        return;
                    }
                    else
                    {
                        DataRow tempRow = dt.NewRow();
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            tempRow[i] = dt.Rows[index][i];
                        }
                        dt.Rows.InsertAt(tempRow, index - 1);
                        dt.Rows.RemoveAt(index + 1);
                        dataGridViewBuildings.ClearSelection();
                        dataGridViewBuildings.Rows[index - 1].Selected = true;
                        dataGridViewBuildings.DataSource = dt;
                    }
                }
            }
            catch 
            { 
                //donothing
            }
        }

        private void toolStripButtonDown_Click(object sender, EventArgs e)
        {
            //move down
            try
            {
                if (dt != null)
                {
                    int index = dataGridViewBuildings.SelectedRows[0].Index;
                    if (index == dt.Rows.Count - 1)
                    {
                        return;
                    }
                    else if (index == -1)
                    {
                        return;
                    }
                    else
                    {
                        DataRow tempRow = dt.NewRow();
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            tempRow[i] = dt.Rows[index][i];
                        }
 dt.Rows.InsertAt(tempRow, index + 2); dt.Rows.RemoveAt(index); dataGridViewBuildings.ClearSelection(); dataGridViewBuildings.Rows[index + 1].Selected = true; dataGridViewBuildings.DataSource = dt; } } } catch { //donothing } }


8 将DataGridView与数据源(如MSSQL某张用户表)绑定

思路

1 新建Form, 新建BindingNavigator和DataGridView控件

2 新建BindingSource

3

设置bindingNavigator.BindingSource=bindingSource

设置dataGridView.DataSource=bindingSource

4 设置BindingSource的DataSource属性

此方法缺点:没找到方法修改DataGridView中列名

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DBInterfaceGX;
using DBInterfaceGX.UserInterfaceDB;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //此处引用广西数据库接口内容
        IUser userOperator;

        //Load事件中装载显示数据
        private void Form1_Load(object sender, EventArgs e)
        {

            BindingSource bindingSource = new BindingSource();
            //绑定
            dataGridView1.DataSource = bindingSource;
            bindingNavigator1.BindingSource = bindingSource;
            //绑定bindingSource
            userOperator = new DbOperatorLinq();
            bindingSource.DataSource = userOperator.CurUserTable;
           
        }

        //保存用户修改到数据库
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                Validate();
                userOperator.SubmitAllChangeOnUserTable();
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            { MessageBox.Show(ex.ToString()); }
        }
    }
}


9 绑定DataGridView与数据库中某张表(控件流)

菜单栏>data>data source>add new data source>database>dataset>选择数据连接>选择所需要的表>Finish。得到下图所示结果



点击"user_table"拖动其进入右侧的form,系统将生成一系列控件。得到下图所示结果:



选择“DataGridView”,选择Column属性,对其中的HeaderText字段进行修改。可以实现修改列标题的效果。结果如下图:




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: