(1)数据绑定
首先编辑Columns属性,设置要绑定的列。然后定义如下的成员变量:
string connstr = @"server=.\sqlexpress;initial catalog=MySchool;uid=sa;pwd=123456";
DataSet ds = new DataSet();
SqlDataAdapter da;
编写数据绑定方法LoadData()
private void LoadData() { string strwhere; if (comboBox1.Text == "男") strwhere="sex='男'"; else if (comboBox1.Text == "女") strwhere="sex='女'"; else strwhere="sex='男' or sex='女'"; //using (SqlConnection conn = new SqlConnection(connstr)) { string sql = "select StudentId,StudentNo,StudentName,Sex from Student where " + strwhere; da = new SqlDataAdapter(sql, connstr); ds.Tables.Clear(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } int rowNumber = 1; foreach (DataGridViewRow row in dataGridView1.Rows) { row.HeaderCell.Value = rowNumber.ToString(); rowNumber++; } }
在窗体加载事件中调用LoadData()方法:
private void StudentListForm_Load(object sender, EventArgs e)
{
LoadData();
}
(2)更新DataGridView中的数据,当用户修改数据后,点击“保存修改”按钮,更新数据。代码如下:
SqlCommandBuilder cmdb = new SqlCommandBuilder(da);
da.Update(ds);
LoadData(); //重新绑定数据
(3)为DataGridView添加右键菜单,供用户删除整行数据。先设置DataGridView的SelectionMode属性为FullRowSelect,然后编写代码:
private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count== 0) { MessageBox.Show("请选择!"); return; } if (MessageBox.Show("确认要删除吗?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { using (SqlConnection conn = new SqlConnection(connstr)) { string sql = "delete from Student where StudentId=" + (int)dataGridView1.SelectedRows[0].Cells[0].Value; SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); cmd.ExecuteNonQuery(); } LoadData(); //重新绑定数据 } }
(4) 要显示SqlCommandBuilder自动构造的语句,可以用下面的代码:
SqlCommandBuilder cmdb = new SqlCommandBuilder(dp);
MessageBox.Show(cmdb.GetDeleteCommand().CommandText);
MessageBox.Show(cmdb.GetInsertCommand().CommandText);
MessageBox.Show(cmdb.GetUpdateCommand().CommandText);
MessageBox.Show(dp.SelectCommand.CommandText);
(5)也可以自己构造InsertCommand、UpdateCommand、DeleteCommand命令,代码如下:
string sqlconn = @"server=.\sqlexpress;database=student;uid=sa;pwd=sa";
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(sqlconn);
SqlDataAdapter dp=new SqlDataAdapter("select * from student",conn);
dp.Fill(ds,"student");
DataRow r=ds.Tables["student"].NewRow();
r["studentid"]="09888888";
r["studentname"]="test";
ds.Tables["student"].Rows.Add(r);
SqlCommand insertCmd = new SqlCommand("insert into student(studentid,studentname) values(@studentid,@studentname)", conn);
insertCmd.Parameters.Add("@studentid", SqlDbType.VarChar, 8,"studentid");
insertCmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50,"studentname");
dp.InsertCommand = insertCmd;
dp.Update(ds.Tables[0]);
如果除了插入,还有更新、删除,则需要同时构造对应的UpdateCommand、DeleteCommand命令,否则会出错。
所以,用SqlCommandBuilder代码比较简洁,但灵活性较差。
(6)DataGridView.CellStateChanged事件作用
在单元格的状态更改时(例如,当单元格失去或获得焦点时)发生。 要触发该事件,SelectionMode属性不能用FullRowSelect,要用CellSelect.
(7)DataGridView.CellValueChanged事件作用
CellValueChanged事件在单元格的值改变,并且是在焦点离开单元格时发生。用代码绑定数据时,也会触发该事件!
(8)DataGridView控件在最左边列显示序号
///简单的方法:
绑定数据后,用下面的代码
int rowNumber = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.HeaderCell.Value = rowNumber.ToString();
rowNumber++;
}
但序号是2位数的话,显示不清楚,列宽不够。要修改DataGridView控件的RowHeadersWidth属性。
////第2种方法,能让箭头都不显示
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rowHeaderBounds = new Rectangle
(
2, e.RowBounds.Top,
this.dataGridView1.RowHeadersWidth - 2, e.RowBounds.Height - 1
);
using (Brush backbrush =
new SolidBrush(SystemColors.Control))
{
e.Graphics.FillRectangle(backbrush, rowHeaderBounds);
}
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
}
(9)取消自动生成列
dataGridView1.AutoGenerateColumns = false;
在Visual Studio 2013中,DataGridView控件的属性窗口中没有AutoGenerateColumns属性,故只能通过代码来设置这个属性。