Devexpress GridControl下拉框实现联动
实现效果
1.先在设计界面绑定数据列
1.点击设计器
2.绑定数据列
2. 绑定GridView的 FocusedRowChanged事件
//定义两个下拉框 _RIcmbtype:不良分类 _RIcmbdefect:不良信息
RepositoryItemComboBox _RIcmbtype = new RepositoryItemComboBox();
//设置下拉框的字体样式
_RIcmbtype.AppearanceDropDown.Font = new Font("Tahoma", 11);
_RIcmbtype.AppearanceDropDown.Options.UseFont = true;
RepositoryItemComboBox _RIcmbdefect = new RepositoryItemComboBox();
private void gvmain_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (gvmain.FocusedRowHandle >= 0)
{
_RIcmbtype.Items.Clear();
if (typeInfos.Count > 1)
{
foreach (var key in typeInfos)
{
_RIcmbtype.Items.Add(new ComboBoxItem(key.bug_typename));
}
}
gvmain.Columns.ColumnByName("colbug_typename").ColumnEdit = _RIcmbtype;
// 为第一列的下拉框添加EditValueChanged事件处理程序
_RIcmbtype.EditValueChanged += _RIcmbtype_EditValueChanged;
_RIcmbdefect.EditValueChanged += _RIcmbdefect_EditValueChanged;
}
}
3. 绑定下拉框的EditValueChanged事件
private void _RIcmbtype_EditValueChanged(object sender, EventArgs e)
{
// 获取当前行的索引
int rowIndex = gvmain.FocusedRowHandle;
if (rowIndex >= 0)
{
var s = (DevExpress.XtraEditors.ComboBoxEdit)sender;
// 获取当前选中的值
string selectedValue = s.EditValue.ToString();
// gvmain.GetRowCellValue(rowIndex, "列名") 这种方法是获取不到选中的值的,原因是选择了,但是实际还未渲染到数据上去就触发了这个事件;
//获取被选中的类型并给所在行赋值 PS:下面4行代码为业务代码 不用看
var type = typeInfos.First(a => a.bug_typename == selectedValue);
dataInfo[rowIndex].bug_typeid = type.bug_id;
dataInfo[rowIndex].bug_typecode = type.bug_typecode;
dataInfo[rowIndex].bug_typename = type.bug_typename;
//通过选择的下拉框的值来获取第二个下拉框的数据
var list = defectInfos.Where(a => a.bug_typename == selectedValue).ToList();
_RIcmbdefect.Items.Clear();
foreach (var key in list)
{
_RIcmbdefect.Items.Add(new ComboBoxItem(key.bug_describe));
}
//设置列的ColumnEdit 为下拉框
gvmain.Columns.ColumnByName("colbug_describe").ColumnEdit = _RIcmbdefect;
// 刷新第二列以显示新的下拉选项
gvmain.InvalidateRow(rowIndex);
}
}