千家信息网

在Windows Form 中绑定非bool类型数据CheckBox控件的示例分析

发表于:2025-02-03 作者:千家信息网编辑
千家信息网最后更新 2025年02月03日,今天就跟大家聊聊有关在Windows Form 中绑定非bool类型数据CheckBox控件的示例分析,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所
千家信息网最后更新 2025年02月03日在Windows Form 中绑定非bool类型数据CheckBox控件的示例分析

今天就跟大家聊聊有关在Windows Form 中绑定非bool类型数据CheckBox控件的示例分析,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

CheckBox的checked属性不能直接绑定非bool型的数据,因此作了下面这个扩展。

使用的时候,需要先设置两个属性
CheckedValue ----选中时代表的值
UnCheckedValue ----未选中时代表的值

例如
CheckedValue = "男"
UnCheckedValue = "女"

然后绑定数据到bindText属性

例如:
enjoyCheckBox1.DataBindings.Add("BindText",ds,"cname");


源码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace Enjoy.Interface.Control
{
///


/// EnjoyCheckBox 的摘要说明。
///

public class EnjoyCheckBox : System.Windows.Forms.CheckBox
{
///
/// 必需的设计器变量。
///

private System.ComponentModel.Container components = null;

public EnjoyCheckBox()
{
// 该调用是 Windows.Forms 窗体设计器所必需的。
InitializeComponent();

// TODO: 在 InitializeComponent 调用后添加任何初始化

}

///


/// 清理所有正在使用的资源。
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region 组件设计器生成的代码
///


/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
///

private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion

private object m_BindText;
private object m_CheckedValue;
private object m_UnCheckedValue;
///


/// 绑定数据库的属性
///

public object BindText
{
get
{
return m_BindText;
}
set
{
m_BindText = value;
if ((m_BindText!=null)&&(CheckedValue!=null)&&(UnCheckedValue!=null))
{
if (m_BindText.Equals(CheckedValue))
{
if (!this.Checked)
{
this.Checked = true;
}
}
if (m_BindText.Equals(UnCheckedValue))
{
if (this.Checked)
{
this.Checked = false;
}
}
}
}
}

///


/// 选中时代表的(数据库中的)值
///

public object CheckedValue
{
get
{
return m_CheckedValue;
}
set
{
m_CheckedValue = value;
}
}

///


/// 未选中时代表的(数据库中的)值
///

public object UnCheckedValue
{
get
{
return m_UnCheckedValue;
}
set
{
m_UnCheckedValue = value;
}
}
protected override void OnCheckedChanged(EventArgs e)
{
base.OnCheckedChanged(e);
if (this.Checked)
{
BindText = CheckedValue;
}
if (!this.Checked)
{
BindText = UnCheckedValue;
}
}


}
}

看完上述内容,你们对在Windows Form 中绑定非bool类型数据CheckBox控件的示例分析有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

0