C# dataGridView类的几个常用功能

本文介绍了在C#中如何使用dataGridView控件,并提供了添加行头的示例代码,帮助开发者理解其基本操作。

添加控件DataGridView后,添加行头:
在这里插入图片描述

界面

在这里插入图片描述

示例代码:
namespace dataGridViewTest
{
public partial class Form1 : Form
{
public int i = 0;
public Form1()
{
InitializeComponent();
}

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridViewRst.Rows.Clear();
    }

    private void buttoAdd_Click(object sender, EventArgs e)
    {
        //添加数据
        dataGridViewRst.Rows.Add();
        dataGridViewRst[0, i].Value = i + 1;
        dataGridViewRst[1, i].Value = Math.Round(3.173, 2);
        dataGridViewRst[2, i].Value = Math.Round(4.923, 2);
        dataGridViewRst[3, i].Value = Math.Round(5.678, 2);
        dataGridViewRst[4, i].Value = Math.Round(6.456, 2);

        i++;
    }

    private void buttonClear_Click(object sender, EventArgs e)
    {
        //清除所有
        dataGridViewRst.Rows.Clear();
        i = 0;
    }

    private void buttonModify_Click(object sender, EventArgs e)
    {
        //获取总行数
        int totalRowsCnt = dataGridViewRst.Rows.Count;

        dataGridViewRst[3, 1].Value = Math.Round(8.173, 2);
        // 获取单元格数据
        double k = (double)dataGridViewRst[3, 1].Value;
        //设置单元格背景色
        dataGridViewRst.Rows[1].Cells[3].Style.BackColor = Color.Yellow;
        //设置单元格前景色
        dataGridViewRst.Rows[1].Cells[3].Style.ForeColor = Color.Green;

        MessageBox.Show("xing");
        //这个表达也可以
        dataGridViewRst.Rows[1].Cells[3].Value = Math.Round(6.173, 2);
        //禁止编辑
        dataGridViewRst.Rows[1].Cells[3].ReadOnly = true;
    }

    private void buttonSelModify_Click(object sender, EventArgs e)
    {
        //修改选择中单元的数据
 int R = this.dataGridViewRst.CurrentRow.Index;
        int C = this.dataGridViewRst.CurrentCell.ColumnIndex;

        dataGridViewRst.Rows[R].Cells[C].Value = Math.Round(0.00, 2);
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值