在Winform程序中,经常需要对datagridview中的数据进行可编辑性操作。将一般控件“绑定”到datagridview中,在操作中更能体现“多功能”。下面以datagridview中输入密码格式的字段为例。
一、在winform中添加datagridview,和一个textbox控件;
二、在textbox的PasswordChar属性修改为“*”,visible为False;
三、分别添加如下事件:
1 private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
2 { 3 if (dataGridView1.CurrentCell.ColumnIndex == 3)//第三列为密码 4 { 5 dataGridView1.Controls.Add(txtPassword); 6 if (txtPassword.ReadOnly==false) 7 { 8 txtPassword.Visible = true; 9 } 10 } 11 }
1 private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
2 { 3 DataGridViewCell cell = dataGridView1.CurrentCell; 4 if (cell!=null) 5 { 6 if (cell.OwningColumn.Index==3) 7 { 8 Rectangle rect = dataGridView1.GetCellDisplayRectangle(cell.ColumnIndex,cell.RowIndex,true); 9 txtPassword.Size = rect.Size; 10 txtPassword.Top = rect.Top; 11 txtPassword.Left = rect.Left; 12 } 13 } 14 }
四、预期结果如下