引入控件
效果:
属性 列集合 Columns
列对象 Column
属性 选择模式 SelectionMode
一般使用整行选中
FullRowSelect
属性 自动列宽度 AutoSizeColumnsMode
是否一次可选多个 MultiSelect
是否可编辑单元格 ReadOnly
自动列宽度 AutoSizeColumnsMode
属性 是否包含行标题的列 RowHeadersVisible
控件绑定数据源
DataGridView对象.DataSource = DataSet对象.Tables[表名称]
为列绑定数据
属性
DataPropertyName
当前行的类
DataGridViewRow
获取当前行
DataGridView对象.CurrentRow
获取当前选中行的集合
DataGridView.SelectedRows
获取当前行的所有单元格
DataGridView对象.CurrentRow.Cells
获取当前行的所有单元格中下标为n的单元格
DataGirdView对象.CurrentRow.Cells[n]
获取单元格对象的值
DataGirdView对象[列索引,列索引]
获取指定行列得的单元格
DataGiedView对象.CurrentCell
获取单元格所在行的行索引
单元格.RowIndex
获取选中的单元格集合
DataGridView对象.selectedCells
获取选中的单元格集合中第n号索引的单元格
DataGiedView对象.SelectedCells[n]
DataGirdView控件的删 改以及修改行内文字
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication18
{
public partial class Form1 : Form
{
SqlDataAdapter adapter;
DataSet ds = new DataSet();
SqlConnection conn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//加载方法
loading();
}
//加载方法定义
public void loading() {
//数据集
//清空一下仓库
if (ds.Tables.Count > 0) {
ds.Tables["hero"].Clear();
}
//sql语句
String sql = "select * from rz";
//连接对象
//连接类 连接对象名称 = new 连接类(连接字符串)
String connString = "Data Source=.;Initial Catalog=bg;Integrated Security=True";
conn = new SqlConnection(connString);
//小车对象
//小车类 小车名称 = new 小车类(sql,连接对象)
adapter = new SqlDataAdapter(sql, conn);
//把小车卸货到仓库
adapter.Fill(ds, "hero");
//核心操作
//关闭自动列的添加
dataGridView1.AutoGenerateColumns = false;
//控件绑定数据源
//控件对象.DataSource = 仓库.Tables[表名称]
dataGridView1.DataSource = ds.Tables["hero"];
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void tsmiSubmit_Click(object sender, EventArgs e)
{
//更新数据
//实例化一个更新用的对象
SqlCommandBuilder buil = new SqlCommandBuilder(adapter);
//小车更新数据
adapter.Update(ds,"hero");
//提示内容
MessageBox.Show("更新成功");
}
private void 删除行DToolStripMenuItem_Click(object sender, EventArgs e)
{
//最终目的,获得选中行的第一个单元格
//1.获得选中的行
DataGridViewRow curentRow = dataGridView1.CurrentRow;
//2.获得该行的第0号索引的单元格
DataGridViewCell currentCell = curentRow.Cells["id"];
//3.获得该单元格的value值
String value = currentCell.Value.ToString();
//4.通过连接式删除数据
//通过连接对象删除这个数据
String sql = "delete from rz where id =" + value;
//新建一个执法者
SqlCommand cmd = new SqlCommand(sql, conn);
//打开连接
try
{
//可能会出错的问题
conn.Open();
// 执法者方法调用
int n = cmd.ExecuteNonQuery();
// 输出一下结果
MessageBox.Show("删除成功,影响行数为:" + n);
//重新load一下数据
loading();
}
catch
{
//提示出错
MessageBox.Show("error");
}
finally {
//提示出错
conn.Close();
}
}
}
}
效果展示:
原图
删除后
点击更新后更新数据库