C#里面的datagridview的使用

最常见的数据绑定:
string sqlStr=数据库查询语句;
DataManager db = new DataManager();
DataSet ds = db.ExcuteSelectCmd(sqlStr);
DataGridView.DataSource = ds.Tables[0];
对DataGridViewCheckBoxColumn列进行动态添加,赋值,判定选中
添加:
DataGridViewCheckBoxColumn select = new DataGridViewCheckBoxColumn();
select.HeaderText = " 选择";
select.Width = 100;
dataGridView1.Columns.Insert(0, select);//添加到dataGridView
赋值:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
chk.Value=true;

}

控制其显示状况即当.Value = false时显示为未选中,为ture是显示为选中,此时需要设置其readonly属性为ture,否则只有当选中其他时才会有反应!

(这个是我后来加的,查了好长时间,如果对你有用,支持一下!)


判定选中:
for (int i = 0; i < dataGridView1.Rows.Count ; i++)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0];
if (chk != null && (bool)chk.FormattedValue)
{

}
}
对单元格的点击事件响应:(对其他,如按钮等的响应也可以一样的处理)
private void CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 需要的列的号)
{
string str = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Trim();
txt_areaAmend.Text = str;
pne_areaAmend.Visible = false;
}
}
设置其选择的模式: 在其属性中设置SelectionMode,可以让其选择是整行还是整列,然后通过 groundID = dataGridView1.SelectedRows[0].Cells ["宗地编号"].Value.ToString().Trim();//获得所选记录的宗地编码
对其进行删除操作 dt.Rows[i].Delete();
posted @ 2009-06-22 09:09  与时俱进  阅读(1059)  评论(0编辑  收藏  举报
友情链接:同里老宅院民居客栈