14. DataGridView数据控件

15 篇文章 4 订阅

DataGridView数据控件

开发WinForms应用程序需要使用数据库存储数据。使用DataGridView控件可以快速地将数据库中的数据显示给用户,并且可以通过DataGridView控件直接对数据进行操作,大大增强了操作数据库的效率。

1 DataGridView控件概述

DataGridView控件提供一种强大而灵活的以表格形式显示数据的方式。可以使用DataGridView控件来显示少量数据的只读视图,也可以对其进行缩放以显示特大数据集的可编辑视图。使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据。将数据绑定到DataGridView控件非常简单和直观,在大多数情况下,只需设置DataSource属性即可。DataGridView控件具有极高的可配置性和可扩展性,他提供了大量的属性、方法和事件,可以用来对该控件的外观和行为进行自定义。当需要在Windows窗体应用程序中显示表格数据时,首先考虑使用DataGridView控件。若要以小型网格显示只读或者使用户能够编辑具有数百万条记录的表。DataGridView控件将提供可以方便的进行编程以及有效利用内存的解决方案。

2 在DataGridView控件中显示数据

通过DataGridView控件显示数据表中的数据,首先需要使用DataAdapter对象查询指定的数据,然后通过该对象的Fill方法填充DataSet,最后设置DataGridView控件的DataSource属性为DataSet的表格数据。DataSource属性用于获取或设置DataGridView控件显示数据的数据源。
在用DataGridView控件显示数据时,可以将Columns[列的索引号]属性的Visible属性设置为False,以隐藏指定的列。

语法:

public Object DataSource {get: set; }
//属性值:包含DataGridView控件要显示的数据对象 

实例 :

private void Form1_Load(object sender, EventArgs e)
{
    string ConStr = "Data Source=.;Initial Catalog=TJHIS;Integrated Security=True";
    SqlConnection conn = new SqlConnection(ConStr);
    conn.Open();
    try
    {
        if (conn.State == ConnectionState.Open)
        {
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter("select * from  student ", conn);
            sda.Fill(ds,"student");
            dataGridView1.DataSource = ds.Tables[0];
        }
    }
    catch (Exception)
    {
        throw;
    }
}

效果:
在这里插入图片描述

3 获取DataGridView控件中的当前单元格

若要与DataGridView进行交互,通常要求通过编程方式发现哪个单元格处于活动状态。如果需要更改当前单元格,可通过DataGridView控件的CurrentCell属性来获取当前单元格信息。
CurrentCell属性用于获取当前处于活动状态的单元格。
可以通过DataGridView控件的SelectedCells属性获取该控件中被选中的单元格信息。

语法:

public DataGridViewCell CurrentCell {get; set; }
//属性值:表示当前单元格的DataGridViewCell ,如果没有当前单元格,则为空引用。默认值是第一列中的第一个单元格,如果控件中没有单元格,则为空引用。

实例:

DataSet ds = null;
SqlDataAdapter sda;
SqlConnection conn;
private void Form1_Load(object sender, EventArgs e)
{
    string ConStr = "Data Source=.;Initial Catalog=TJHIS;Integrated Security=True";
    conn = new SqlConnection(ConStr);
    conn.Open();
    try
    {
        if (conn.State == ConnectionState.Open)
        {
            sda = new SqlDataAdapter("select * from  student ", conn);
            ds = new DataSet();
            sda.Fill(ds,"student");
            dataGridView1.DataSource = ds.Tables[0];
        }
    }
    catch (Exception)
    {
        throw;
    }
}
private void button1_Click(object sender, EventArgs e)
{
    string msg = string.Format("第{0}行,第{1}列", dataGridView1.CurrentCell.RowIndex, dataGridView1.CurrentCell.ColumnIndex);
    label1.Text = msg;
}

效果:
在这里插入图片描述

4 直接在DataGridView控件中修改数据

在DataGridView控件中修改数据,主要用到DataTable的ImportRow方法和DataAdapter对象的Update方法。实现的过程是通过DataTable的ImportRow方法将更改后的数据复制到一个DataTable中,然后通过DataAdapter对象的Update方法,将DataTable中的数据更新到数据库中。
ImportRow方法用于将DataRow复制到DataTable中,保留任何属性设置以及初始值和当前值。

语法:

public void ImportRow(DataRow row)
//row:要导入的DataRow

注意:
默认情况下,用户可以通过在当前的DataGridView文本框单元格中输入或按F2键来编辑该单元格的内容。在控件单元格中编辑内容的前提是DataGridView控件已启用以及单元格、行、列和控件的ReadOnly属性都设置为false。ReadOnly属性用于指示用户是否可以编辑DataGridView控件的单元格。

实例:

DataSet ds = null;
SqlDataAdapter sda;
SqlConnection conn;
private void button1_Click(object sender, EventArgs e)
{
    string ConStr = "Data Source=.;Initial Catalog=TJHIS;Integrated Security=True";
    conn = new SqlConnection(ConStr);
    conn.Open();
    try
    {
        if (conn.State == ConnectionState.Open)
        {
            sda = new SqlDataAdapter("select * from  student ", conn);
            ds = new DataSet();
            sda.Fill(ds, "student");
            dataGridView1.DataSource = ds.Tables[0];
            //禁止显示行标题
            dataGridView1.RowHeadersVisible = false;
            //使用循环设置控件的列宽
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                dataGridView1.Columns[0].Width = 84;
            }

        }
        button1.Enabled = false;
        //主键列设置为只读
        dataGridView1.Columns[0].ReadOnly = true;
    }
    catch (Exception)
    {
        throw;
    }
    conn.Close();
}
private void button2_Click_1(object sender, EventArgs e)
{
    if (dbUpdate())
    {
        MessageBox.Show("修改成功!!");
    }
}
private DataTable dbconn(string strSql)
{
    conn.Open();
    this.sda = new SqlDataAdapter(strSql, conn);
    DataTable dtSelect =new DataTable();
    int rnt = this.sda.Fill(dtSelect);
    conn.Close();
    return dtSelect;
}
private  Boolean dbUpdate()
{
    string strSql = "select* from  student";
    DataTable dtUpdate = this.dbconn(strSql);
    dtUpdate.Rows.Clear();
    DataTable dtShow = (DataTable)this.dataGridView1.DataSource;
    for (int i = 0; i < dtShow.Rows.Count; i++)
    {
        //使用ImportRow方法复制dtShow中的值
        dtUpdate.ImportRow(dtShow.Rows[i]);
    }
    try
    {
        this.conn.Open();
        SqlCommandBuilder CommandBuilder = new SqlCommandBuilder(this.sda);
        this.sda.Update(dtUpdate);
        this.conn.Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
        return false;
    }
    dtUpdate.AcceptChanges();//提交更改
    return true;

}

效果:

在这里插入图片描述

5 当选中DataGridView控件中的行时显示不同的颜色

可以利用DataGridView控件的SelectionMode、ReadOnly和SelectionBackColor属性实现当选中DataGridView控件中的行时显示不同的颜色。

  1. SelectionMode用于设置如何选择DataGridView的单元格

语法:

public DataGridViewSelectionMode SelectionMode {get; set;}
//属性值:DataGridViewSelectionMode值之一,默认为RowHeaderSelect

DataGridViewSelectionMode枚举值及说明:

枚举值说明
ellSelect可以选定一个或多个单元格
ColumnHeaderSelect可以通过单击列的标头单元格选定此列,通过单击某个单元格可以单独选定此单元格
FullColumnSelect通过单击列的标头或该列所包含的单元格选定整个列
FullRowSelect通过单击列的标头或是该行所包含的单元格选定整个行
RowHeaderSelect通过单击列的标头单元格选定此行,通过单击某个单元格可以单独选定此单元格

说明:
在更改SelectionMode属性的值时,会清除当前的选择,所以在更改行的颜色时,要注意更改和选中的顺序。

  1. ReadOnly属性用于设置是否可以编辑DataGridView控件的单元格

语法:

public bool ReadOnly {get; set; }
//属性值:如果用户不能编辑DataGridView控件的单元格,则为true,否则为false,默认为false
  1. SelectionBackColor属性用于设置DataGridView单元格在被选定时的背景色
    SelectionBackColor属性包含在DataGridViewCellStyle类中,所以调用此属性之前要调用DataGridViewCellStyle属性。
    语法:
public bool SelectionBackColor {get; set; }
//属性值:Color,它表示选定单元格的背景的,默认为Empty

实例:

DataSet ds = null;
SqlDataAdapter sda;
SqlConnection conn;
private void Form1_Load(object sender, EventArgs e)
{
    string ConStr = "Data Source=.;Initial Catalog=TJHIS;Integrated Security=True";
    conn = new SqlConnection(ConStr);
    conn.Open();
    try
    {
        if (conn.State == ConnectionState.Open)
        {
            sda = new SqlDataAdapter("select * from  student ", conn);
            ds = new DataSet();
            sda.Fill(ds, "student");
            dataGridView1.DataSource = ds.Tables[0];
            //整行选择
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.ReadOnly = true;
            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.YellowGreen;
        }
     
    }
    catch (Exception)
    {
        throw;
    }
    conn.Close();
}

效果:
在这里插入图片描述

6 禁止在DataGridView控件中添加和删除行

通过设置DataGridView控件的公共属性AllowUserToAddRows、AllowUserToDeleteRows和ReadOnly,可以禁止在DataGridView控件中添加和删除行。
AllowUserToAddRows属性设置一个值,该值指示是否向用户显示添加行的选项;
AllowUserToDeleteRows属性设置一个值,该值指示是否允许用户从DataGridView控件中删除行;
ReadOnly属性设置一个指示网格是否处于只读模式的值。

实例:

dataGridView1.AllowUserToAddRows = false; //禁止添加行
dataGridView1.AllowUserToDeleteRows = false;  //禁止添加列
dataGridView1.ReadOnly = true;  //只读

7 使用Columns和Rows属性添加数据

通过设置DataGridView控件的Columns和Rows属性值,可以向数据控件DataGridView添加数据项,使其能够手动添加数据。

  1. Columns属性用于获取一个包含控件中所有列的集合
public DataGridViewColummCollection Rows {get; }
//属性值:一个DataGridViewColummCollection  ,包含DataGridView控件中所有的列
  1. Rows属性获取一个集合,该集合包含DataGridView控件中的所有行。
public DataGridViewRowCollection Rows {get; }
//属性值:一个DataGridViewRowCollection ,包含DataGridView控件中所有的行

说明:
如果想要在DataGridView控件的单元格中添加下拉列表,可以通过DataGridViewComboBoxColumn类来实现。

实例:

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.ColumnCount = 4;  //列数
    dataGridView1.ColumnHeadersVisible = true ;   //显示列标题
    //设置标题列的样式
    DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();
    columnHeaderStyle.BackColor = Color.Beige;
    columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
    dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

    dataGridView1.Columns[0].Name = "编号";
    dataGridView1.Columns[1].Name = "姓名";
    dataGridView1.Columns[2].Name = "年龄";
    dataGridView1.Columns[3].Name = "性别";

    string[] row1 = new string[] { "001", "唐三藏", "30", "男" };
    string[] row2 = new string[] { "002", "孙悟空", "1000", "男" };
    string[] row3 = new string[] { "003", "猪八戒", "1000", "男" };
    string[] row4 = new string[] { "004", "沙和尚", "1000", "男" };
    string[] row5 = new string[] { "005", "白龙马", "1000", "男" };
    string[] row6 = new string[] { "005", "王路飞", "18", "公" };
    object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };
    foreach (string[] rowArray in rows)
    {
        dataGridView1.Rows.Add(rowArray);
    }
}

效果:

在这里插入图片描述

  • 12
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值