winform中DataGridView添加ComboBox的最终解决方案(点击ComboBox默认显示当前行的内容)

当当网9周年店庆,特价,全场免运费,快来抢吧!

 

第一:

数据绑定ComBoBox控件


先在窗体设计时拖一个ComBoBox控件,然后在里面的ITEMS设好你要下拉项,或者从数据库中的表绑定,这个估计都会。


第二:

// 将下拉列表框加入到DataGridView控件中,这句放在绑定DataGridView之后写。
在窗体的Load方法中加入:g_DataGridView.Controls.Add(g_ComBoBox);也就是把ComBoBox控件添加到DataGridView控件中

第三:
在DataGridView控件的CurrentCellChanged方法中写如下代码:

DataGridViewCell CurrnetCell = g_View.CurrentCell;
if (CurrnetCell != null && CurrnetCell.OwningColumn.Name == " 列名 " )
{
Rectangle TmpRect
= g_DataGridView.GetCellDisplayRectangle(CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, true );
g_ComBoBox.Text
= CurrnetCell.Value.ToString();
g_ComBoBox.Size
= TmpRect.Size;
g_ComBoBox.Top
= TmpRect.Top;
g_ComBoBox.Left
= TmpRect.Left;
g_ComBoBox.Visible
= true ;
}
else
{
g_ComBoBox.Visible
= false ;
}

特别注意这一句:g_ComBoBox.Text = CurrnetCell.Value.ToString();

如果ComBoBox绑定的是两个值,即编码和名称,那么请把这句改为

g_ComBoBox.SelectedValue= CurrnetCell.Value.ToString();
要不然点击ComBoBox控件后默认的值不是当前表中选中的值。

 


第四:

在ComBoBox控件的SelectedIndexChanged方法中写:

g_DataGridView.CurrentCell.Value = g_ComBoBox.Text;

 

注意:如果有编码改成:

g_DataGridView.CurrentCell.Value = g_ComBoBox.SelectedValue.ToString();

 

好了,大功告成了。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值