.Net的DataGridView控件中,提供了一種列的類型,叫 DataGridViewButtonColumn ,這種列類型是展示為一個 按鈕,可以給button賦予相應的text,並且,此button可以用來做處理事件的判斷依據。
DataGridViewButtonColumn,雖然在UI展現上,是一個BUTTON的樣子,但是,它的實際形態,並不是傳統意義的BUTTON,而是渲染出來的樣式,完全是painting的效果而已。所以,對於傳統意義的BUTTON的那一套在這里都失效啦
代碼實現:
//在datagridview中添加button按鈕 DataGridViewButtonColumn btn = new DataGridViewButtonColumn(); btn.Name = "btnModify"; btn.HeaderText = "修改"; btn.DefaultCellStyle.NullValue = "修改"; dataGridView1.Columns.Add(btn);
然后在DataGridView的CellContentClick事件中寫類似如下代碼:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { //點擊button按鈕事件 if (dataGridView1.Columns[e.ColumnIndex].Name == "btnModify" && e.RowIndex >= 0) { //說明點擊的列是DataGridViewButtonColumn列 DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex]; IPEntity ipentity = new IPEntity(); ipentity.ipName = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value); ipentity.ipPart = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value); ipentity.ipStart = Convert.ToString(dataGridView1.CurrentRow.Cells[2].Value); ipentity.ipEnd = Convert.ToString(dataGridView1.CurrentRow.Cells[3].Value); bool flag = selectIp.UpdateIP(ipentity); if (flag) { MessageBox.Show("更新成功!"); } else { MessageBox.Show("更新失敗!"); } } }