刚要做一个项目,要求实现的一个功能为用户将自已的购买记录上报。原来设计的方式为在窗口中添加几个输入控件,每填写一条记录点击确定进行上报。
最后用户提出这种方式使用起来太麻烦,上报一条就是点击一下确定。并且不能查看单次整体上报的情况。
根据用户的需求,最后确定在页面中放一个datagridview控件,用户在其中输入要上报的内容。将所有要上报和内容输入完成后上报。这样有一些字段,如产品类别 等,这些比较固定的字段就需要设一个下拉列表供用户选择类别。另外像 购买时间等一些字段需要显示一个datetimepicker供用户选择时间.这就需要在datagridview 中添加combobox,datetimepicker 等控件。
实现步骤如下:
1.在页面中添加一个datagridview, 一个combobox, 还有一个datetimepicker控件.
2.首先将datagridview是editmode属性设置为EditOnEnter 这样当用户就不需要双击datagridview才能输入数据.
3.在页的page_load事件中将combobox 和 datetimepicker控件加入datagridview.
- private void Form1_Load(object sender, EventArgs e)
- {
- this.dataGridView1.Controls.Add(this.cob_type);
- this.dataGridView1.Controls.Add(this.dateTimePicker1);
- }
4.为datagridview添加CurrentCellChanged事件。代码如下:
- private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
- {
- DataGridViewCell CurrnetCell = this.dataGridView1.CurrentCell;
- if (CurrnetCell != null && CurrnetCell.OwningColumn.Name == "产品类别")
- {
- Rectangle TmpRect = this.dataGridView1.GetCellDisplayRectangle(CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, true);
- if (CurrnetCell.Value != null)
- {
- this.cob_type.Text = CurrnetCell.Value.ToString();
- }
- this.cob_type.Size = TmpRect.Size;
- this.cob_type.Top = TmpRect.Top;
- this.cob_type.Left = TmpRect.Left;
- this.cob_type.Visible = true;
- }
- else if (CurrnetCell != null && CurrnetCell.OwningColumn.Name == "购买日期")
- {
- Rectangle TmpRect = this.dataGridView1.GetCellDisplayRectangle(CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, true);
- if (CurrnetCell.Value != null)
- {
- this.dateTimePicker1.Value = Convert.ToDateTime(CurrnetCell.Value);
- }
- this.dateTimePicker1.Size = TmpRect.Size;
- this.dateTimePicker1.Top = TmpRect.Top;
- this.dateTimePicker1.Left = TmpRect.Left;
- this.dateTimePicker1.Visible = true;
- }
- else
- {
- this.cob_type.Visible = false;
- this.dateTimePicker1.Visible = false;
- }
- }
5.然后为combobox添加SelectedIndexChanged,将选择的值添加到datagridview对应列
- private void cob_type_SelectedIndexChanged(object sender, EventArgs e)
- {
- string temp= this.cob_type.Text;
- this.dataGridView1.CurrentCell.Value =temp;
- if (temp == "电脑")
- {
- this.dataGridView1.CurrentRow.Cells["计量单位"].Value = "台";
- }
- else if (temp == "钢笔")
- {
- this.dataGridView1.CurrentRow.Cells["计量单位"].Value = "支";
- }
- //可能根据实际需要写相应的代码
- }
6 为datetimepicker添加CloseUp事件,当用户选定时间后将选定的时间添加到datagridview对应列
- private void dateTimePicker1_CloseUp(object sender, EventArgs e)
- {
- this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Value.ToString();
- }
这样就完成了通过datagridview添加记录了。并且得到了很好的用户体验.
效果如图: