C#高级:DataGridView的详解

发布于:2024-03-02 ⋅ 阅读:(65) ⋅ 点赞:(0)

一、每条数据增加一个按钮,点击输出对应实体

请先确保正确添加实体的名称和文本:

private void button6_Click(object sender, EventArgs e)
{
    //SQL查询到数据,存于list中
    List<InforMessage> list = bll.QueryInforMessage();//含有字段:Title PublishTime UserName Content
    // 清空现有数据
    dataGridView1.Rows.Clear();
    //添加数据
    foreach (var item in list)
    {
        //绑定数据,注意你的不一定是dataGridView1
        int rowIndex = dataGridView1.Rows.Add();
        dataGridView1.Rows[rowIndex].Cells["Title"].Value = item.Title;
        dataGridView1.Rows[rowIndex].Cells["PublishTime"].Value = item.PublishTime;
        dataGridView1.Rows[rowIndex].Cells["UserName"].Value = item.UserName;
        dataGridView1.Rows[rowIndex].Cells["Content"].Value = "点击查看";//按钮名称
        // 将数据实体关联到行的 Tag 属性上以便后续处理
        dataGridView1.Rows[rowIndex].Tag = item;
    }
}

// 在 DataGridView 的 CellContentClick (点击某一单元格)事件中处理内容按钮点击事件
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["Content"].Index && e.RowIndex >= 0)//若点击了标签为【Content】列的按钮
    {
        // 获取当前行对应的实体对象【注意修改此处InforMessage类】
        var item = dataGridView1.Rows[e.RowIndex].Tag as InforMessage;
        //将list实体中的content展示出来
        if (item != null)
        {
            MessageBox.Show(item.Content, "内容详情");
        }
    }
}

 二、输出选中的实体信息

【代码如下】

 private void Form1_Load(object sender, EventArgs e)
 {
    //sql查表
     List<Student> list = bll.QueryStudent();
     // 清空现有数据
     dataGridView1.Rows.Clear();
     //添加数据
     foreach (var item in list)
     {
         int rowIndex = dataGridView1.Rows.Add();
         dataGridView1.Rows[rowIndex].Cells["ID"].Value = item.ID;
         dataGridView1.Rows[rowIndex].Cells["Name"].Value = item.Name;
         dataGridView1.Rows[rowIndex].Tag = item;
     }
 }

 private void button1_Click(object sender, EventArgs e)//点击触发
 {
     //获取选中的实体(在窗体上定义好了)
    var result = selectedStudent;
 }

 private void dataGridView1_SelectionChanged(object sender, EventArgs e)//选中触发
 {
     if (dataGridView1.SelectedRows.Count > 0)
     {
         DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
         selectedStudent = (Student)selectedRow.Tag;//获取选中的实体
     }
     else
     {
         selectedStudent = null;
     }
 }

 三、小结

1.增:  建议用textbox、combobox等工具增,而不是直接datagridview新增,一来麻烦,二来输入工具不能多样化。

2.删:建议如标题一,每条数据加一个删除按钮,方便操作

3.改:建议如标题二,选中某条数据然后将数据信息转移到textbox上,label显示“您已选中xxx数据”,然后点击button去修改相应信息(选中数据和点击按钮都能获取到对应实体)

4.查:同第2条

5.如果单纯用datagridview作增删查改,虽然能实现,但是代码复杂难以维护,而且输入条件单一,容易操作失误,不建议这么做。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到