在DataGridView的列中表示按钮时,使用DataGridViewButtonColumn可以实现。
按钮上表示的文字就是所在单元格所表示的文字(所就是说,使用FormattedValue属性取得的文字列)。但是,如果DataGridViewButtonColumn.UseColumnTextForButtonValue为True时,在DataGridViewButtonColumn.Text属性中设定的文字列,就会在所有的按钮上被表示出来。
#### 下面的代码是在DataGridView中追加按钮列的例子。所有按钮上的文字列为「点击阅览」。
//DataGridViewButtonColumn作成
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
//设定列的名字
column.Name = "Button";
//在所有按钮上表示"点击阅览"
column.UseColumnTextForButtonValue = true;
column.Text = "点击阅览";
//向DataGridView追加
DataGridView1.Columns.Add(column);
#### 获得按钮被点击
点击DataGridViewButtonColumn的按钮时,会触发DataGridView.CellContentClick事件。这个事件处理器可以检测被点击的按钮是否在列中,如果在就会被触发。
下面的例子就是当按钮被点击时,取得是第几行的按钮被点击了。
//CellContentClick事件处理器
private void DataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;//这行语句也可以不要,如果已经创建了dgv,详见航道系统的代码。
//如果是"Button"列,按钮被点击
if (dgv.Columns[e.ColumnIndex].Name == "Button")//此处索引列可以使name、也可以使headertext,看具体的设置。
{
MessageBox.Show(e.RowIndex.ToString() +
"行的按钮被点击了。");
}
}
#### 按钮的无效状态
如果想让DataGridViewButtonColumn的按钮为无效状态(Button控件的Enabled属性设定为False时的状态),原则上说是不可能的。如果真的想设定,在「禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮」中有详细的说明。
#### 往列里面加入字符,只能在text的类型中使用。
//foreach (DataGridViewRow row in dgvPic.Rows)
// {
// row.Cells[Column1.Index].Value = "OK";
// }
##### datagridview清空数据
DataTable dt = (DataTable)dgvData.DataSource;
dt.Rows.Clear();
dgvData.
按钮上表示的文字就是所在单元格所表示的文字(所就是说,使用FormattedValue属性取得的文字列)。但是,如果DataGridViewButtonColumn.UseColumnTextForButtonValue为True时,在DataGridViewButtonColumn.Text属性中设定的文字列,就会在所有的按钮上被表示出来。
#### 下面的代码是在DataGridView中追加按钮列的例子。所有按钮上的文字列为「点击阅览」。
//DataGridViewButtonColumn作成
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
//设定列的名字
column.Name = "Button";
//在所有按钮上表示"点击阅览"
column.UseColumnTextForButtonValue = true;
column.Text = "点击阅览";
//向DataGridView追加
DataGridView1.Columns.Add(column);
#### 获得按钮被点击
点击DataGridViewButtonColumn的按钮时,会触发DataGridView.CellContentClick事件。这个事件处理器可以检测被点击的按钮是否在列中,如果在就会被触发。
下面的例子就是当按钮被点击时,取得是第几行的按钮被点击了。
//CellContentClick事件处理器
private void DataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;//这行语句也可以不要,如果已经创建了dgv,详见航道系统的代码。
//如果是"Button"列,按钮被点击
if (dgv.Columns[e.ColumnIndex].Name == "Button")//此处索引列可以使name、也可以使headertext,看具体的设置。
{
MessageBox.Show(e.RowIndex.ToString() +
"行的按钮被点击了。");
}
}
#### 按钮的无效状态
如果想让DataGridViewButtonColumn的按钮为无效状态(Button控件的Enabled属性设定为False时的状态),原则上说是不可能的。如果真的想设定,在「禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮」中有详细的说明。
#### 往列里面加入字符,只能在text的类型中使用。
//foreach (DataGridViewRow row in dgvPic.Rows)
// {
// row.Cells[Column1.Index].Value = "OK";
// }
##### datagridview清空数据
DataTable dt = (DataTable)dgvData.DataSource;
dt.Rows.Clear();
dgvData.