以下是针对DataGridView控件的常见使用的一个查阅说明:
(1)、获取DataGridView控件中的当前单元格
行索引:dataGridView1.CurrentCell.RowIndex.ToString();
列索引:dataGridView1.CurrentCell.ColumnIndex.ToString();
(2)、复制DataSet
DataSet ds_copy = ds.Copy(); //调用一个已经存在的数据集的Copy方法,返回值仍然是一个DataSet
dataGridView1.DataSource = ds_copy.Tables[0];
(3)、选中DataGridView控件中的行时显示不同颜色
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //整行被选中
dataGridView1.ReadOnly = true; //DataGridView控件中的数据为只读,不能修改
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.YellowGreen; // 设置被选中行的背景颜色
(4)、禁止在DataGridView控件中添加和删除行
dataGridView1.AllowUserToAddRows = false; //属性设为false
dataGridView1.AllowUserToDeleteRows = false; //属性设为false
dataGridView1.ReadOnly = false; ////DataGridView控件中的数据可以修改
(5)、使用Rows和Columns属性添加数据
dataGridView1.ColumnCount = 4; //列数为4
dataGridView1.ColumnHeadersVisible = true; //列的头标题可见
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();
columnHeaderStyle.BackColor = Color.Beige;
columnHeaderStyle.Font = new Font("宋体",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[]{"1001","张三",22,"男"};
string[] row2 = new string[]{"1002","李四",24,"女"};
string[] row3 = new string[]{"1003","王五",25,"男"};
//将所有内容放在一个object的数据中
object[] rows = new object[]{row1,row2,row3};
//遍历object数组,将所有内容添加到DataGridView中去
foreach(string[] rowArray in rows)
{
dataGridView1.Rows.Add(rowArray);
}
(6)、间接在DataGridView控件中修改数据
在dataGridView1_CellClick(object sender,EventArgs e)方法中添加如下代码:
txtID.Text = dataGridView1.SelectedCells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedCells[1].Value.ToString();
txtPwd.Text = dataGridView1.SelectedCells[2].Value.ToString();
txtQQ.Text = dataGridView1.SelectedCells[3].Value.ToString();
此段代码是用于在点击某行时,将该行内容填写到下方的TextBox控件中,用于显示和后来的修改。
添加一个修改按钮,用于修改文本框TextBox中的内容,其中ID字段不让修改,是主键。
//修改数据
DataTable dt = ds.Tables[0];
da.FillSchema(dt, SchemaType.Mapped);
DataRow dr = dt.Rows.Find(txtID.Text);
dr["username"] = txtName.Text.Trim();
dr["password"] = txtPwd.Text.Trim();
dr["qq"] = txtQQ.Text.Trim();
SqlCommandBuilder scb = new SqlCommandBuilder(da);
da.Update(dt);
MessageBox.Show("修改成功!");