Dev控件GridControl实现CheckBox列和ComBox列
1、在sql语句中添加空白行,如select c1,c2 null c3 from xxx;
2、将sql语句查询结果与gdc绑定CmmFrm.BestFitGridViewColumnsWidth(gdc_lines, sql,2);
3、将上述空白列绑定为RepositoryItemCheckEdit控件,并添加事件
RepositoryItemCheckEdit re = new RepositoryItemCheckEdit();
re.QueryCheckStateByValue += new DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventHandler(Re_QueryCheckStateByValue);//定义这个事件是关键,因为就靠它了
gdv_lines.Columns[2].ColumnEdit = re;
4、事件实现:
void Re_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
{
string val = "";
if (e.Value != null)
{
val = e.Value.ToString();
}
else
{
val = "";//默认为不选中
}
switch (val)
{
case"True":
e.CheckState = CheckState.Checked;
break;
case"False":
e.CheckState = CheckState.Unchecked;
break;
case"Yes":
goto case"True";
case"No":
goto case"False";
case"1":
goto case"True";
case"0":
goto case"False";
default:
e.CheckState = CheckState.Unchecked; //默认状态,如果默认选择,则改为Checked
break;
}
e.Handled = true;
}
5、整个gdv控件要设为可编辑,但除了chekbox列外,其它列要禁止出现编辑,这要靠gdc控件的ShowingEditor事件实现
private void gdv_lines_ShowingEditor(object sender, CancelEventArgs e)
{
if (gdv_lines.FocusedColumn.AbsoluteIndex != 2)
e.Cancel = true;
}
6、遍历、检索
for (int i = 0; i < gdv_lines.DataRowCount; i++)
{
DataRow dr=gdv_lines.GetDataRow(i);
string ck = dr[2].ToString();
if (ck == "True")
{
...
}
7、程序设置选择状态
bool res = true;
if (gdv_lines.GetDataRow(0)[2].ToString() == "True") res = false;
for (int i = 0; i < gdv_lines.DataRowCount; i++) gdv_lines.GetDataRow(i)[2] = res;
///////////////////////////////////////////////////
另外,添加CombBox的方法,还不完善
// gdvLevel.BeginUpdate(); //开始视图的编辑,防止触发其他事件
// gdvLevel.BeginDataUpdate(); //开始数据的编辑
CmmFrm.BestFitGridViewColumnsWidth(gdcLevel, lvels, 1, false, false);
gdcLevel.DataSource = lvels;
gdvLevel.Columns[0].Visible = false;
RepositoryItemComboBox riCombo = new RepositoryItemComboBox();
riCombo.Items.AddRange(new string[] { "夏", "目视", "目视以下", "(含)以下" });
gdcLevel.RepositoryItems.Add(riCombo);
gdvLevel.Columns["其它"].ColumnEdit = riCombo;
//目前这种添加combbox的方法有缺陷,主要表现在1、不能设置为DorpDownList样式。2、选择后要敲回车,选择才能现在Cell中,否则焦点移走,选择就消失。
//有两篇文章解决这个问题,有时间梳理下
//https://yq.aliyun.com/articles/55052
//https://www.cnblogs.com/lonelyxmas/p/3906496.html
RepositoryItemCheckEdit riCkbox = new RepositoryItemCheckEdit();
riCkbox.ValueChecked = false;
gdcLevel.RepositoryItems.Add(riCkbox);
gdvLevel.Columns["选择"].ColumnEdit = riCkbox;
gdvLevel.EndDataUpdate();//结束数据的编辑
gdvLevel.EndUpdate(); //结束视图的编辑