网站建设中网站需求分析,设计网站推荐html代码,台州网站优化,一般通过手机号加微信的好友一、每条数据增加一个按钮#xff0c;点击输出对应实体
请先确保正确添加实体的名称和文本#xff1a; private void button6_Click(object sender, EventArgs e)
{//SQL查询到数据#xff0c;存于list中ListInforMessage list bll.QueryInforMessage();//含有字段…一、每条数据增加一个按钮点击输出对应实体
请先确保正确添加实体的名称和文本 private void button6_Click(object sender, EventArgs e)
{//SQL查询到数据存于list中ListInforMessage list bll.QueryInforMessage();//含有字段ID Title PublishTime UserName Content// 清空现有数据dataGridView1.Rows.Clear();//添加数据foreach (var item in list){//绑定数据注意你的不一定是dataGridView1列表没有ID不要写下去ID也会一起打包到Tagint 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类】,此处能获取到ID虽然没有显示在界面上但也绑定到Tag了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查表ListStudent 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作增删查改虽然能实现但是代码复杂难以维护而且输入条件单一容易操作失误不建议这么做。