以下是針對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("修改成功!");