WinForm 中ComboBox 绑定总结

合集下载

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的⼏种⽅法1.⽤DataSet和DataTable为DataGridView提供数据源String strConn = "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";SqlConnection conn = new SqlConnection(strConn);String sql= "select * from EMPLOYEE ";conn.Open();SqlCommand cmd = new SqlCommand(sqlId, conn);SqlDataAdapter da = new SqlDataAdapter(cmd);DataSet ds = new DataSet();da.Fill(ds, "EMPLOYEE");dataGridView1.DataSource = ds;this.dataGridView1.AutoGenerateColumns = false;//是否⾃动⽣成列dataGridView1.DataMember = "EMPLOYEE";conn.Close();2.创建DataGridViewRow 对象Add添加⾏String sql_conn= "Data Source=.;Initial Catalog=His;User ID=sa;Password=*****";System.Data.DataTable table =return_table(sql_conn);foreach (System.Data.DataRow date in table.Rows){DataGridViewRow newRow = new DataGridViewRow();newRow.CreateCells(this.dataGridView1);newRow.Cells[0].Value = date[0].ToString();newRow.Cells[1].Value = date[1].ToString();newRow.Cells[2].Value = date[2].ToString();newRow.Cells[3].Value = date[3].ToString();newRow.Cells[4].Value = date[4].ToString();dataGridView1.Rows.Add(newRow);}public System.Data.DataTable return_table(string sql_conn){SqlConnection conn = new SqlConnection(sql_conn);SqlDataReader reader = null;conn.Open();SqlCommand command = new SqlCommand("selectRegID,Name,Area,RoomNO,BedNO from EMPLOYEE", conn);reader = command.ExecuteReader();return ConvertToDataTable(reader);}public DataTable ConvertToDataTable(SqlDataReader dataReader)//SqlDataReader转换为DataTable{DataTable dt = new DataTable();DataTable schemaTable = dataReader.GetSchemaTable();try{//动态构建表,添加列foreach (DataRow dr in schemaTable.Rows){DataColumn dc = new DataColumn();//设置列的数据类型dc.DataType = dr[0].GetType();//设置列的名称dc.ColumnName = dr[0].ToString();//将该列添加进构造的表中dt.Columns.Add(dc);}//读取数据添加进表中while (dataReader.Read()){DataRow row = dt.NewRow();//填充⼀⾏数据for (int i = 0; i < schemaTable.Rows.Count; i++){row[i] = dataReader[i].ToString();}dt.Rows.Add(row);row = null;}dataReader.Close();schemaTable = null;return dt;}catch (Exception ex){//抛出异常throw new Exception(ex.Message); }}。

Winform常用控件

Winform常用控件

1.数据显示:DataGridView(DataGridView 控件提供用来显示数据的可自定义表。

使用 DataGridView 类,可以自定义单元格、行、列和边框)。

文本编辑:TextBox(显示设计时输入的文本,它可由用户在运行时编辑或以编程方式更改)。

RichTextBox(使文本能够以纯文本或 RTF 格式显示)。

MaskedTextBox(约束用户输入的格式)。

2.信息显示:Label(显示用户无法直接编辑的文本)。

LinkLabel(将文本显示为 Web 样式的链接,并在用户单击该特殊文本时触发事件。

该文本通常是到另一个窗口或网站的链接)。

StatusStrip(通常在父窗体的底部使用有框架的区域显示有关应用程序的当前状态的信息)。

ProgressBar(向用户显示操作的当前进度)。

3.从列表中选择:CheckedListBox(显示一个可滚动的项列表,每项旁边都有一个复选框)。

ComboBox(显示一个下拉式项列表)。

DomainUpDown(显示用户可用向上和向下按钮滚动的文本项列表)。

ListBox(显示一个文本项和图形项(图标)列表)。

ListView(在四个不同视图之一中显示项。

这些视图包括纯文本视图、带有小图标的文本视图、带有大图标的文本视图和详细信息视图)。

NumericUpDown(显示用户可用向上和向下按钮滚动的数字列表)。

TreeView (显示一个节点对象的分层集合,这些节点对象由带有可选复选框或图标的文本组成)。

4.图形显示:PictureBox(在一个框架中显示图形文件(如位图和图标)。

5.图形存储:ImageList(充当图像储存库。

ImageList 控件和及其包含的图像可以在不同的应用程序中重用)。

6.值的设置:CheckBox(显示一个复选框和一个文本标签。

通常用来设置选项)。

CheckedListBox(显示一个可滚动的项列表,每项旁边都有一个复选框)。

MSFlexGrid进行Combox,Check,ListBox等的绑定实例

MSFlexGrid进行Combox,Check,ListBox等的绑定实例

'Download by Option ExplicitPrivate Sub Form_Load()Dim x As IntegerWith FlxGd.ColAlignment(-1) = 1 'all Left allignedFor x = 1 To .Cols - 1.TextMatrix(0, x) = "Col " + Str(x)NextFor x = 1 To FlxGd.Rows - 1.TextMatrix(x, 0) = "Row " + Str(x)Next.Row = 1.Col = 1.CellBackColor = &HC0FFFF 'lt. yellowEnd WithCombo1_LoadList1_LoadCheck1_LoadEnd SubPrivate Sub cmdAddRow_Click()AddGridRowEnd SubPrivate Sub cmdDelRow_Click()DeleteGridRowEnd SubPrivate Sub FlxGd_EnterCell()FlxGd.CellBackColor = &HC0FFFF 'lt. yellowFlxGd.Tag = "" 'clear temp storage End SubPrivate Sub FlxGd_LeaveCell()If FlxGd.Col = 2 ThenFlxGd = Format$(FlxGd, "#") 'alpha-number format ElseIf FlxGd.Col = 3 Then 'this is for CheckboxesIf Check1.Value = 0 ThenFlxGd.Text = "No"End IfEnd IfFlxGd = Format$(FlxGd, "0.00")End IfFlxGd.CellBackColor = &H80000005End SubPrivate Sub FlxGd_KeyDown(KeyCode As Integer, Shift As Integer) Select Case KeyCodeCase 46 '<Del>, clear cellFlxGd.Tag = FlxGd 'assign to temp storageFlxGd = ""End SelectEnd SubPrivate Sub FlxGd_KeyPress(KeyAscii As Integer)Select Case KeyAsciiCase 13 'ENTER keyAdvance_Cell 'advance new cellCase 8 'BackspaceIf Len(FlxGd) ThenFlxGd = Left$(FlxGd, Len(FlxGd) - 1)End IfCase 27 'ESCIf FlxGd.Tag > "" Then 'only if not NULLFlxGd = FlxGd.Tag 'restore original textEnd IfCase ElseFlxGd = FlxGd + Chr(KeyAscii)End SelectEnd SubPrivate Sub FlxGd_Click()If Combo1.Visible = True ThenCombo1.Visible = FalseFlxGd.CellBackColor = &H80000005 'whiteElseIf List1.Visible = True ThenList1.Visible = FalseFlxGd.CellBackColor = &H80000005ElseIf Check1.Visible = True ThenCheck1.Visible = FalseFlxGd.CellBackColor = &H80000005End IfEnd IfEnd IfIf FlxGd.Col = 1 Then ' Position and size the ListBox, then show it.List1.Width = FlxGd.CellWidthList1.Left = FlxGd.CellLeft + FlxGd.LeftList1.Top = FlxGd.CellTop + FlxGd.TopList1.Text = FlxGd.TextList1.Visible = TrueElseIf FlxGd.Col = 2 Then ' Position and size the ComboBox, then show it.Combo1.Width = FlxGd.CellWidthCombo1.Left = FlxGd.CellLeft + FlxGd.LeftCombo1.Top = FlxGd.CellTop + FlxGd.TopCombo1.Text = FlxGd.TextCombo1.Visible = TrueElseIf FlxGd.Col = 3 Then ' Position and size the CheckBox, then show it.Check1.Width = FlxGd.CellWidthCheck1.Left = FlxGd.CellLeft + FlxGd.LeftCheck1.Top = FlxGd.CellTop + FlxGd.TopIf FlxGd.Text = "Yes" ThenCheck1.Value = 1ElseIf FlxGd.Text = "No" ThenCheck1.Value = 0End IfEnd IfCheck1.Visible = TrueEnd IfEnd IfEnd IfEnd SubPrivate Sub Check1_Click() ' Place the selected Yes/No into the Cell and hide the CheckBox.If FlxGd.Col = 3 ThenIf Check1.Value = 1 ThenFlxGd.Text = "是"ElseIf Check1.Value = 0 ThenFlxGd.Text = "否"End IfEnd IfCheck1.Visible = FalseEnd IfEnd SubPrivate Sub Check1_Load() ' Load the Checkbox.Check1.Visible = FalseCheck1.Value = FalseCheck1.Caption = "请选择"Check1.Width = FlxGd.CellWidthEnd SubPrivate Sub List1_Load() ' Load the ListBox's list.List1.Visible = FalseList1.Width = FlxGd.CellWidthList1.AddItem ""List1.AddItem "小狗"List1.AddItem "小猫"List1.AddItem "金鱼"List1.ListIndex = 0End SubPrivate Sub List1_Click() ' Place the selected item into the Cell and hide the ListBox.If FlxGd.Col = 1 ThenFlxGd.Text = List1.TextList1.Visible = FalseEnd IfEnd SubPrivate Sub Combo1_Click() ' Place the selected item into the Cell and hide the ComboBox.If FlxGd.Col = 2 ThenFlxGd.Text = Combo1.TextCombo1.Visible = FalseEnd IfEnd SubPrivate Sub Combo1_Load() ' Load the ComboBox's list.FlxGd.RowHeightMin = Combo1.HeightCombo1.Visible = FalseCombo1.Width = FlxGd.CellWidthCombo1.AddItem "1"Combo1.AddItem "2"Combo1.AddItem "3"End SubPrivate Sub FlxGd_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) Dim Row As Integer, Col As IntegerRow = FlxGd.MouseRowCol = FlxGd.MouseColIf Button = 2 And (Col = 0 Or Row = 0) ThenFlxGd.Col = IIf(Col = 0, 1, Col)FlxGd.Row = IIf(Row = 0, 1, Row)PopupMenu MnuFGridRowsEnd IfEnd SubPrivate Sub MnuFGridAddRow_Click()AddGridRowEnd SubPrivate Sub AddGridRow()With FlxGd.Rows = .Rows + 1.Row = .Rows - 1.TextMatrix(.Row, 0) = "Row " + Str(.Row)End WithEnd SubPrivate Sub mnuDeleteGridRow_Click()DeleteGridRowEnd SubPrivate Sub DeleteGridRow()Dim Row As Integer, n As Integer, x As IntegerWith FlxGdIf .Rows > 2 Then 'make sure we don't del a rowRow = .RowFor n = 1 To .Cols - 1If .TextMatrix(Row, n) > "" Thenx = 1Exit ForEnd IfNextIf x Thenn = MsgBox("Data in Row" + Str$(Row) + ". Delete anyway?", vbYesNo, "Delete Row...")End IfIf x = 0 Or n = 6 Then 'no exist. data or YESFor n = .Row To .Rows - 2 'move exist data up 1 rowFor x = 1 To FlxGd.Cols - 1.TextMatrix(n, x) = .TextMatrix(n + 1, x)NextNextIf Row = .Rows - 1 Then 'set new cursor row.Row = .Rows - 2End If.Rows = .Rows - 1 'delete last rowEnd IfEnd IfEnd WithEnd SubPrivate Sub End_Click()EndEnd SubPrivate Sub Advance_Cell() 'advance to next cell With FlxGd.HighLight = flexHighlightNever 'turn off hi-liteIf .Col < .Cols - 1 Then.Col = .Col + 1ElseIf .Row < .Rows - 1 Then.Row = .Row + 1 'down 1 row.Col = 1 'first columnElse.Row = 1.Col = 1End IfEnd IfIf .CellTop + .CellHeight > .Top + .Height Then.TopRow = .TopRow + 1 'make sure row is visibleEnd If.HighLight = flexHighlightAlways 'turn on hi-lite End WithEnd Sub。

C#数据绑定(1)—简单的文本框绑定

C#数据绑定(1)—简单的文本框绑定

C#数据绑定(1)—简单的⽂本框绑定经常写⽤⼀个TextBox显⽰某个对象,然后编辑之后再保存的程序。

以前都是在TextBox_TextChanged事件中修改对象的值,或者保存的时候再读取TextBox.Text属性保存对象的值。

这样⽐较⿇烦,⽽且经常容易出错。

后来了解了C#的数据绑定,发现能够很好的解决这个问题。

1.⾸先C#的TextBox本⾝就带数据绑定功能。

下⾯的代码就是把_myData对象的"TheValue"属性绑定到textBox1和textBox2的"Text"属性。

最后⼀个参数不同:1)其中DataSourceUpdateMode.OnPropertyChanged表⽰textBox1.Text发⽣变化,_myData.TheValue也变化,叫双向绑定。

2)DataSourceUpdateMode.Never表⽰Text1.Text变化不影响_myData.TheValue的值,是单向绑定。

private void Form1_Load(object sender, EventArgs e){_myData = new MyData();textBox1.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.OnPropertyChanged);textBox2.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.Never);}2.也许有⼈留意到了,为什么上⾯的叫"双向绑定"呢?如果_myData.TheValue的值变化了,两个⽂本框的Text会变化吗?不错,仅在textBox上数据绑定还不叫双向绑定,对象数据变化要通知绑定该对象的控件才⾏。

combobox控件实现多列显示

combobox控件实现多列显示

combobox控件实现多列显⽰该程序主要参考codeProject上的⼀个程序,链接已失去,不过要想其致敬!默认的combobox是不提供多列显⽰的,所以这⾥要⽤绘制的⽅法显⽰该功能,主要是重写combobox。

其中combobox有个属性DrawMode,需将其设为DrawMode.OwnerDrawVariable,原因如下:从MSDN摘录.Normal控件中的所有元素都由操作系统绘制,并且元素⼤⼩都相等。

OwnerDrawFixed控件中的所有元素都是⼿动绘制的,并且元素⼤⼩都相等。

OwnerDrawVariable控件中的所有元素都由⼿动绘制,元素⼤⼩可能不相等。

具体步骤如下:实例以datatable为数据源,数据源也可以是arraylist或通过add()⽅法添加int columnPadding = 5;private float[] columnWidths = new float[0]; //项宽度private String[] columnNames = new String[0]; //项名称private int valueMemberColumnIndex = 0; //valueMember属性列所在的索引///<summary>///绑定数据源或更改数据源时发⽣///</summary>///<param name="e"></param>protected override void OnDataSourceChanged(EventArgs e){base.OnDataSourceChanged(e);InitializeColumns();}///<summary>///设置ValueMember属性发⽣///</summary>///<param name="e"></param>protected override void OnValueMemberChanged(EventArgs e){base.OnValueMemberChanged(e);InitializeValueMemberColumn();}///<summary>///显⽰下拉框的时候触发///</summary>///<param name="e"></param>protected override void OnDropDown(EventArgs e){base.OnDropDown(e);this.DropDownWidth = (int)CalculateTotalWidth(); //计算combobox下拉框的总宽度}///<summary>///初始化数据源各列的名称///</summary>private void InitializeColumns(){PropertyDescriptorCollection propertyDescriptorCollection = DataManager.GetItemProperties();columnWidths = new float[propertyDescriptorCollection.Count];columnNames = new String[propertyDescriptorCollection.Count];for (int colIndex = 0; colIndex < propertyDescriptorCollection.Count; colIndex++){String name = propertyDescriptorCollection[colIndex].Name;columnNames[colIndex] = name;}}///<summary>///返回ValueMember在显⽰列中的索引位置///</summary>private void InitializeValueMemberColumn(){int colIndex = 0;foreach (String columnName in columnNames){if (pare(columnName, ValueMember, true, CultureInfo.CurrentUICulture) == 0){valueMemberColumnIndex = colIndex;break;}colIndex++;}}///<summary>///计算combobox下拉框的总宽度///</summary>///<returns></returns>private float CalculateTotalWidth(){columnPadding = 5;float totWidth = 0;foreach (int width in columnWidths){totWidth += (width + columnPadding);}//总宽度加上垂直滚动条的宽度return totWidth + SystemInformation.VerticalScrollBarWidth;}绘制字符串所使⽤的两个⽅法:///<summary>///获得各列的宽度和项的总宽度///引发 MeasureItem 事件///</summary>///<param name="e"></param>protected override void OnMeasureItem(MeasureItemEventArgs e){base.OnMeasureItem(e);if (DesignMode)return;for (int colIndex = 0; colIndex < columnNames.Length; colIndex++){//如果 ListControl 项是被给定了该项以及属性名称的对象的属性,则返回该项的当前值string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex])); SizeF sizeF = e.Graphics.MeasureString(item, Font); //返回显⽰项字符串的⼤⼩columnWidths[colIndex] = Math.Max(columnWidths[colIndex], sizeF.Width);}float totWidth = CalculateTotalWidth(); //计算combobox下拉框项宽度e.ItemWidth = (int)totWidth; //设置combobox下拉框项宽度}///<summary>///绘制下拉框的内容///引发 DrawItem 事件///</summary>///<param name="e"></param>protected override void OnDrawItem(DrawItemEventArgs e){base.OnDrawItem(e);if (DesignMode)return;e.DrawBackground();Rectangle boundsRect = e.Bounds;int lastRight = 0;using (Pen linePen = new Pen(SystemColors.GrayText)){using (SolidBrush brush = new SolidBrush(ForeColor)){if (columnNames.Length == 0){e.Graphics.DrawString(Convert.ToString(Items[e.Index]), Font, brush, boundsRect);}else{//循环各列for (int colIndex = 0; colIndex < columnNames.Length; colIndex++){string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex]));boundsRect.X = lastRight; //列的左边位置boundsRect.Width = (int)columnWidths[colIndex] + columnPadding; //列的宽度lastRight = boundsRect.Right;if (colIndex == valueMemberColumnIndex)//如果是valueMember项{using (Font boldFont = new Font(Font, FontStyle.Bold)){//绘制项的内容e.Graphics.DrawString(item, boldFont, brush, boundsRect);}}else{//绘制项的内容e.Graphics.DrawString(item, Font, brush, boundsRect);}//绘制各项间的竖线if (colIndex < columnNames.Length - 1){e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, boundsRect.Right, boundsRect.Bottom); }}}}}e.DrawFocusRectangle();}界⾯层绑定数据源:DataTable dataTable = new DataTable("Employees");dataTable.Columns.Add("Employee ID", typeof(String));dataTable.Columns.Add("Name", typeof(String));dataTable.Columns.Add("Country", typeof(String));dataTable.Rows.Add(new String[] { "1", "James", "USA" });dataTable.Rows.Add(new String[] { "2", "Mary", "UK" });dataTable.Rows.Add(new String[] { "3", "Jack", "Japan" });有需要源码的朋友同样可以到我的群中下载.。

【原创】Winform下拉框自动选择实现

【原创】Winform下拉框自动选择实现

【原创】Winform下拉框⾃动选择实现适⽤环境:Winform开发,VS2008开发⼯具问题描述:1. 有⼀系列产品,每个产品都有唯⼀产品ID,产品名称。

2. 需要绑定产品到下拉框(ComboBox)中,由于Winform的下拉框控件,不像Web开发中的下拉框控件⼀样,能够直接添加两个元素到每⼀项(Value和Text)。

但是它允许直接添加object对象项,所以反⽽更灵活。

3. 在下拉框中需要显⽰产品信息,并且不只是简单显⽰名称,需要做⼀些特别的处理,因此没法使⽤。

cboxProduct.DisplayMember = "ProductName";cboxProduct.ValueMember = "ProductId";cboxProduct.DataSource = dataTable; //Product Data Source4. 要能够根据产品信息,⾃动选择到特定产品。

解决思路:1. ⾸先我们可以定义⼀个产品信息类,包含产品的各种信息。

在这⾥我们必须要的信息可以作为构造函数的参数,使得实例化产品类必须设置这些信息。

同时对于绑定下拉框信息话,我们还可以提取⼀个公有的类,专门⽤于绑定下拉框时使⽤,因为⼤多数情况下,我们⼀般使⽤下拉框只需要绑定两类信息。

但是信息的数据格式却是不定的,所以可以考虑泛型。

2. 采⽤泛型创建公有下拉框数据类,包含两个属性:Value和Text。

3. 由于Value属性作为我们下拉框索引值,必须是唯⼀的,所以在判断下拉框数据项是否相同时,可以通过判断是否Value是否相同来确定(必须说明的是在这⾥我们并没有强制判断Value值是否唯⼀,你可以在绑定数据时判断),判断两个对象是否相等的⽅法,可以想到考虑重写Equal⽅法来实现。

下⾯我们来看⼀个实际的例⼦实现吧!实例代码:1. 创建⼀个产品类型类(ProductType类),由于产品类型可以是⼀个⽆限级分类(某⼀产品类型下的⼦产品类型层次不定,可能会很多层⼦类型),在下拉框显⽰产品类型时,需要区分⽗⼦产品类型。

C#WinForm下DataGridView单选按钮列和支持三种选择状态的复选框列的实现

C#WinForm下DataGridView单选按钮列和⽀持三种选择状态的复选框列的实现在C# WinForm下做过项⽬的朋友都知道,其中的DataGridView控件默认只⽀持DataGridViewButtonColumn、DataGridViewCheckBoxColumn、DataGridViewComboBoxColumn、DataGridViewImageColumn、DataGridViewLinkColumn和DataGridViewTextBoxColumn六种列类型,如果你想要在DataGridView的列中添加其它的⼦控件,则需要⾃⼰实现DataGridViewColumn和DataGridViewCell,这就意味着你需要从现有的列中继承并改写⼀些⽅法,如实现⼀个⽀持单选按钮的列,或⽀持三种选择状态的多选按钮的列。

上⾯两个截图分别为RadioButton列和⽀持三种状态的CheckBox列在DataGridView中的实现效果,我是在Windows 2003中实现的,因此显⽰的效果跟在XP和Vista下有些区别,Vista下CheckBox的第三种状态(不确定状态)显⽰出来的效果是⼀个实⼼的蓝⾊⽅块。

下⾯我看具体来看看如何实现这两种效果。

要实现⾃定义的DataGridView列,你需要继承并改写两个类,⼀个是基于DataGridViewColumn的,⼀个是基于DataGridViewCell的,因为RadionButton和CheckBox的实现原理类似,因此我们可以将这两种列采⽤同⼀种⽅法实现。

创建DataGridViewDisableCheckBoxCell和DataGridViewDisableCheckBoxColumn两个类,分别继承⾃DataGridViewCheckBoxCell和DataGridViewCheckBoxColumn。

代码如下:public class DataGridViewDisableCheckBoxCell: DataGridViewCheckBoxCell{public bool Enabled { get; set; }// Override the Clone method so that the Enabled property is copied.public override object Clone(){DataGridViewDisableCheckBoxCell cell = (DataGridViewDisableCheckBoxCell)base.Clone();cell.Enabled = this.Enabled;return cell;}// By default, enable the CheckBox cell.public DataGridViewDisableCheckBoxCell(){this.Enabled = true;}// Three state checkbox column cellprotected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,DataGridViewElementStates elementState, object value, object formattedValue, string errorText,DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts){// The checkBox cell is disabled, so paint the border, background, and disabled checkBox for the cell.if (!this.Enabled){// Draw the cell background, if specified.if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background){SolidBrush cellBackground = new SolidBrush(cellStyle.BackColor);graphics.FillRectangle(cellBackground, cellBounds);cellBackground.Dispose();}// Draw the cell borders, if specified.if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border){PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);}// Calculate the area in which to draw the checkBox.CheckBoxState state = CheckBoxState.MixedDisabled;Size size = CheckBoxRenderer.GetGlyphSize(graphics, state);Point center = new Point(cellBounds.X, cellBounds.Y);center.X += (cellBounds.Width - size.Width) / 2;center.Y += (cellBounds.Height - size.Height) / 2;// Draw the disabled checkBox.CheckBoxRenderer.DrawCheckBox(graphics, center, state);}else{// The checkBox cell is enabled, so let the base class, handle the painting.base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);}}}public class DataGridViewDisableCheckBoxColumn : DataGridViewCheckBoxColumn{public DataGridViewDisableCheckBoxColumn(){this.CellTemplate = new DataGridViewDisableCheckBoxCell();}}主要是要实现DataGridViewDisableCheckBoxCell的呈现⽅式,其中设置了CheckBoxState的状态为MixedDisabled,表⽰⽀持三种状态,这个是实现效果的核⼼,如果要实现RadioButton列的效果,只需要将Paint⽅法改成下⾯这样即可:protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,DataGridViewElementStates elementState, object value, object formattedValue, string errorText,DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts){// Draw the cell background, if specified.if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background){SolidBrush cellBackground = new SolidBrush(cellStyle.BackColor);graphics.FillRectangle(cellBackground, cellBounds);cellBackground.Dispose();}// Draw the cell borders, if specified.if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border){PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);}// Calculate the area in which to draw the checkBox.RadioButtonState state = value != null && (SelectedStatus)value == SelectedStatus.Selected ? RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal; Size size = RadioButtonRenderer.GetGlyphSize(graphics, state);Point center = new Point(cellBounds.X, cellBounds.Y);center.X += (cellBounds.Width - size.Width) / 2;center.Y += (cellBounds.Height - size.Height) / 2;// Draw the disabled checkBox.RadioButtonRenderer.DrawRadioButton(graphics, center, state);}使⽤RadioButtonState代替CheckBoxState。

(四十九)c#Winform自定义控件-下拉框(表格)-HZHControls

(四⼗九)c#Winform⾃定义控件-下拉框(表格)-HZHControls 官⽹前提⼊⾏已经7,8年了,⼀直想做⼀套漂亮点的⾃定义控件,于是就有了本系列⽂章。

GitHub:码云:如果觉得写的还⾏,请点个 star ⽀持⼀下吧欢迎前来交流探讨:企鹅群568015492⿇烦博客下⽅点个【推荐】,谢谢NuGetInstall-Package HZH_Controls⽬录⽤处及效果1 List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();2 lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "ID", HeadText = "编号", Width = 70, WidthType = SizeType.Absolute });3 lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Name", HeadText = "姓名", Width = 100, WidthType = SizeType.Absolute });4 lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Age", HeadText = "年龄", Width = 100, WidthType = SizeType.Absolute });5 lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Birthday", HeadText = "⽣⽇", Width = 120, WidthType = SizeType.Absolute, Format = (a) => { return ((DateTime)a).ToString("yyyy-MM-dd"); } });6 lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Sex", HeadText = "性别", Width = 100, WidthType = SizeType.Absolute, Format = (a) => { return ((int)a) == 0 ? "⼥" : "男"; } });7this.ucComboxGrid1.GridColumns = lstCulumns;8 List<object> lstSourceGrid = new List<object>();9for (int i = 0; i < 100; i++)10 {11 TestModel model = new TestModel()12 {13 ID = i.ToString(),14 Age = 3 * i,15 Name = "姓名——" + i,16 Birthday = DateTime.Now.AddYears(-10),17 Sex = i % 218 };19 lstSourceGrid.Add(model);20 }21this.ucComboxGrid1.GridDataSource = lstSourceGrid;准备⼯作此控件继承⾃UCCombox,并且需要表格控件UCDataGridView,如果不了解请移步查看如果你想显⽰树形结构,请移步查看开始我们⾸先需要⼀个弹出的⾯板,那么我们先添加⼀个⽤户控件UCComboxGridPanel,在这个⽤户控件上添加⼀个⽂本框进⾏搜索,添加⼀个表格展⽰数据⼀些属性1 [Description("项点击事件"), Category("⾃定义")]2public event DataGridViewEventHandler ItemClick;3private Type m_rowType = typeof(UCDataGridViewRow);45public Type RowType6 {7get { return m_rowType; }8set9 {10 m_rowType = value;11this.ucDataGridView1.RowType = m_rowType;1415private List<DataGridViewColumnEntity> m_columns = null;1617public List<DataGridViewColumnEntity> Columns18 {19get { return m_columns; }20set21 {22 m_columns = value;23this.ucDataGridView1.Columns = value;24 }25 }26private List<object> m_dataSource = null;2728public List<object> DataSource29 {30get { return m_dataSource; }31set { m_dataSource = value; }32 }3334private string strLastSearchText = string.Empty;35 UCPagerControl m_page = new UCPagerControl();⼀些事件,处理数据绑定1void ucDataGridView1_ItemClick(object sender, DataGridViewEventArgs e)2 {3if (ItemClick != null)4 {5 ItemClick((sender as IDataGridViewRow).DataSource, null);6 }7 }89void txtInput_TextChanged(object sender, EventArgs e)10 {11 timer1.Enabled = false;12 timer1.Enabled = true;13 }1415private void UCComboxGridPanel_Load(object sender, EventArgs e)16 {17 m_page.DataSource = m_dataSource;18this.ucDataGridView1.DataSource = m_page.GetCurrentSource();19 }2021private void timer1_Tick(object sender, EventArgs e)22 {23if (strLastSearchText == txtSearch.InputText)24 {25 timer1.Enabled = false;26 }27else28 {29 strLastSearchText = txtSearch.InputText;30 Search(txtSearch.InputText);31 }32 }3334private void Search(string strText)35 {36 m_page.StartIndex = 0;37if (!string.IsNullOrEmpty(strText))38 {39 strText = strText.ToLower();40 List<object> lst = m_dataSource.FindAll(p => m_columns.Any(c => (c.Format == null ? (p.GetType().GetProperty(c.DataField).GetValue(p, null).ToStringExt()) : c.Format(p.GetType().GetProperty(c.DataField).GetValue(p,41 m_page.DataSource = lst;42 }43else44 {45 m_page.DataSource = m_dataSource;46 }47 m_page.Reload();48 }完整代码1using System;2using System.Collections.Generic;3using ponentModel;4using System.Drawing;5using System.Data;6using System.Linq;7using System.Text;8using System.Windows.Forms;910namespace HZH_boBox11 {12 [ToolboxItem(false)]13public partial class UCComboxGridPanel : UserControl14 {15 [Description("项点击事件"), Category("⾃定义")]16public event DataGridViewEventHandler ItemClick;17private Type m_rowType = typeof(UCDataGridViewRow);1819public Type RowType20 {21get { return m_rowType; }22set23 {24 m_rowType = value;25this.ucDataGridView1.RowType = m_rowType;26 }27 }2829private List<DataGridViewColumnEntity> m_columns = null;3031public List<DataGridViewColumnEntity> Columns32 {33get { return m_columns; }34set35 {36 m_columns = value;37this.ucDataGridView1.Columns = value;38 }39 }40private List<object> m_dataSource = null;4142public List<object> DataSource46 }4748private string strLastSearchText = string.Empty;49 UCPagerControl m_page = new UCPagerControl();5051public UCComboxGridPanel()52 {53 InitializeComponent();54this.ucDataGridView1.Page = m_page;55this.ucDataGridView1.IsAutoHeight = false;56this.txtSearch.txtInput.TextChanged += txtInput_TextChanged;57this.ucDataGridView1.ItemClick += ucDataGridView1_ItemClick;58 }5960void ucDataGridView1_ItemClick(object sender, DataGridViewEventArgs e)61 {62if (ItemClick != null)63 {64 ItemClick((sender as IDataGridViewRow).DataSource, null);65 }66 }6768void txtInput_TextChanged(object sender, EventArgs e)69 {70 timer1.Enabled = false;71 timer1.Enabled = true;72 }7374private void UCComboxGridPanel_Load(object sender, EventArgs e)75 {76 m_page.DataSource = m_dataSource;77this.ucDataGridView1.DataSource = m_page.GetCurrentSource();78 }7980private void timer1_Tick(object sender, EventArgs e)81 {82if (strLastSearchText == txtSearch.InputText)83 {84 timer1.Enabled = false;85 }86else87 {88 strLastSearchText = txtSearch.InputText;89 Search(txtSearch.InputText);90 }91 }9293private void Search(string strText)94 {95 m_page.StartIndex = 0;96if (!string.IsNullOrEmpty(strText))97 {98 strText = strText.ToLower();99 List<object> lst = m_dataSource.FindAll(p => m_columns.Any(c => (c.Format == null ? (p.GetType().GetProperty(c.DataField).GetValue(p, null).ToStringExt()) : c.Format(p.GetType().GetProperty(c.DataField).GetValue(p, 100 m_page.DataSource = lst;101 }102else103 {104 m_page.DataSource = m_dataSource;105 }106 m_page.Reload();107 }108 }109 }View Code1namespace HZH_boBox2 {3partial class UCComboxGridPanel4 {5///<summary>6///必需的设计器变量。

Combo控件属性


AccessibleDescription
AccessibleName AccessibleRole AllowDrop
Anchor
AutoCompleteCustomSource AutoCompleteMode AutoCompleteSource AutoScrollOffset AutoSize BackColor BackgroundImage BackgroundImageLayout BindingContext Bottom
Bounds CanFocus CanSelect
Capture
获取或设置一个值,该值指示控件是否已捕获鼠标. (从 Control 继 承.) 获取或设置一个值, 该值指示控件是否会引起在任何需要在接收焦点时 执行验证的控件上执行验证. (从 Control 继承.) 获取或设置一个值,该值指示是否捕获对错误线程的调用,这些调用访 问控件的 Handle 属性. (从 Control 继承.) 获取表示控件的工作区的矩形. (从 Control 继承.) 获取或设置控件的工作区的高度和宽度. (从 Control 继承.) 获取包含控件的应用程序的公司名称或创建者.(从 Control 继承. ) 获取 IContainer,它包含 Component. (从 Component 继承.) 获取一个值,该值指示控件或它的一个子控件当前是否有输入焦点. (从 Control 继承.) 获取或设置与控件关联的快捷菜单. (从 Control 继承.) 获取或设置与此控件关联的 ContextMenuStrip. (从 Control 继承. ) 获取包含在控件内的控件的集合. (从 Control 继承.) 获取一个值,该值指示控件是否已经创建. (从 Control 继承.) 获取或设置当鼠标指针位于控件上时显示的光标. (从 Control 继 承.) 为该控件获取数据绑定. (从 Control 继承.) 获取或设置此 ComboBox 的数据源. 获取控件的默认背景色. (从 Control 继承.) 获取控件的默认字体. (从 Control 继承.) 获取控件的默认前景色. (从 Control 继承.) 获取或设置要为此 ListControl 显示的属性. (从 ListControl 继 承.) 获取表示控件的显示区域的矩形. (从 Control 继承.) 获取一个值, 该值指示 Control 基类是否在释放进程中. (从 Control 继承.) 获取或设置哪些控件边框停靠到其父控件并确定控件如何随其父级一 起调整大小. (从 Control 继承.) 获取或设置一个值, 该值指示是由您的代码还是由操作系统来处理列表 中的元素的绘制.

access中组合框使用详解

access中组合框使用详解Access中的组合框使用详解组合框(Combo Box)是Microsoft Access中一种常用的控件,它可以让用户在给定的选项中进行选择。

在本文中,我们将详细介绍Access中组合框的使用方法和注意事项。

一、组合框的基本概念组合框是由一个文本框和一个下拉箭头按钮组成的控件。

通过点击下拉箭头按钮,用户可以选择一个或多个选项。

选中的值将显示在文本框中。

组合框可以用于数据输入、数据筛选、数据导航等多种场景。

二、创建组合框在Access中创建组合框非常简单。

首先,在表单或报表的设计视图中选择“工具”选项卡中的“设计”组,然后点击“组合框”按钮。

接下来,在表单或报表上拖动鼠标,绘制出所需大小的组合框。

三、设置组合框的属性组合框的属性决定了它的外观和行为。

在设计视图中选中组合框,然后在属性窗口中可以设置以下常用属性:1. 数据源(Row Source):用于指定组合框的选项列表。

可以选择表格、查询、值列表或SQL语句作为数据源。

2. 列数(Column Count):用于指定组合框显示的列数。

默认为1,如果需要显示多列,则可以适当增加列数。

3. 列宽(Column Widths):用于指定每列的宽度。

多个列的宽度用分号隔开。

例如,"2cm;4cm"表示第一列宽度为2厘米,第二列宽度为4厘米。

4. 值(Value):用于指定组合框的默认值。

可以是具体的值,也可以是与数据源对应的字段。

5. 样式(Style):用于设置组合框的显示样式。

常见的样式有下拉列表(Dropdown List)和下拉框(Dropdown Combo)两种。

四、使用组合框的常见场景1. 数据输入:组合框可以用于数据输入,例如在一个表单中选择客户的名称。

用户可以通过下拉箭头选择客户名称,然后所选的值将显示在文本框中。

2. 数据筛选:组合框还可以用于数据筛选,例如在一个查询表单中选择某个类别的产品。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

WinForm 中ComboBox 绑定总结
1. DataTable
用DataTable直接绑定,只需 要设置DataSource、DisplayMember、ValueMember三个属性即可。

this.cmbConsumeSuperMarket.DataSource = dtSuperMarket;
this.cmbConsumeSuperMarket.DisplayMember = "Name"; this.cmbConsumeSuperMarket.ValueMember
= "ID"; this.cmbConsumeSuperMarket.SelectedIndex = 0;

在使用时使用如下方式,即可取得相应 的ID和Name,这样就可以基本满足业务要求了。
StringTools.ObjectToInt(this.cmbConsumeSuperMarket.SelectedValue);
StringTools.ObjectToStr(this.cmbConsumeSuperMarket.SelectedText);

但如上的问题是,因为ComboBox绑定后默认显示第一项,但需要一项提示性选项,我没有找到什么好方法实现了。
上网看一些人用ComboBox.SelectedIndex = -1或设置ComboBox.Text或初始化设置ComboBox.Items一个项
为初始项或设置ComboBox.DropDownStyle,但 我这里都没达到效果。

本应实现效果A,但以上只能实现B效果,所以以上不符合要求。

效果A 效果B

2. ComboBox.Items.Add
一开始使用时,以为像Asp.net那样有ListItem属性可以使用,但Items只有几个特别简单的属性,还好Add(object
item),所以就只能在object这里作文章了。

所以就把要绑定的item新new 了一个对象,再重写ToString(),如是乎就可以了。
因为在整个页面中,有很多类似的ComboBox控件,所以就小小的抽象了一下,然后就可以便捷的实现效果B了。具体
实现方式如下:
using System.Data;
using System.Windows.Forms;

namespace BlackCore.App.Method
{
//抽象类 DataBindControls 引入抽象方法 dataBindComboBox(……)
public abstract class DataBindControls
{
///
/// 绑定 ComboBox
///
/// ComboBox Control
/// 是否为此控件插入一个默认选项且默认选中
/// 需要绑定的DataTable
/// 显示文字(DisplayMember)
/// ValueMember
public abstract void dataBindComboBox(ComboBox cmb, bool isInsertDefaultItem, DataTable dt, st
ring selectedText, string selectedValue);
}
}

实现抽象即可

using System.Data;
using System.Windows.Forms;
using BlackCore.FinancialLibrary;

namespace BlackCore.App.Method
{
//实现抽象
//类 DataBindControlsImplement 重 写 dataBindComboBox,并提供一个具体实现。
//由 于 DataBindControlsImplement 中没有了抽象成员,因此可以(但并非必须)
将 DataBindControlsImplement 声明为非抽象类。
public class DataBindControlsImplement : DataBindControls
{
public override void dataBindComboBox(ComboBox comboBox, bool isInsertDefaultItem, DataTable
dataTable, string selectedText, string selectedValue)
{
if (dataTable != null && dataTable.Rows != null && dataTable.Rows.Count > 0)
{
if (comboBox.Items.Count > 0)
{
comboBox.Items.Clear();
}
int i = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
//comboBox.SelectedText = StringTools.ObjectToStr(dataRow[selectedText]).Trim ();
//comboBox.SelectedValue = StringTools.ObjectToInt(dataRow[selectedValue]).ToString ();

//BlackCore.BLL.FinancialManage.FMProject bllProject = new BlackCore.BLL.FinancialMana
ge.FMProject();
//BlackCore.Model.FinancialManage.FMProject modelProject = new BlackCore.Model.Financ
ialManage.FMProject();
//modelProject = bllProject.GetModel(StringTools.ObjectToInt(dataRow["ID"]));

//用如下这种方式就只有selectedText,而没有selectedValue
//comboBox.Items.Add(StringTools.ObjectToStr(dataRow[selectedText]).Trim());

//可以存储在ComboBox中的任何种类的对象,而不是字符串。重写toString()方法生成的文本框将
显示。
//这样就可以实现selectedText,selectedValue或更多需要的属性
comboBox.Items.Add(new ComboBoxItemTextValue(StringTools.ObjectToInt(dataRow[sele
ctedValue]).ToString(), StringTools.ObjectToStr(dataRow[selectedText])));
}
if (isInsertDefaultItem)
{
comboBox.Items.Insert(0, "请选择");
}
comboBox.SelectedIndex = 0;
}
}
public class ComboBoxItemTextValue
{
public string selectText;
public string selectValue;

public ComboBoxItemTextValue(string _selectValue, string _selectText)
{
selectValue = _selectValue;
selectText = _selectText;
}
public override string ToString()
{
return selectText;
}
}

}
}

ComboBox的绑定
DataBindControlsImplement implement = new BlackCore.App.Method.DataBindControlsImplement();
implement.dataBindComboBox(this.searchCmbConsumeMarket, true, bllMarket.GetList("").Tables[0], "N
ame", "ID");

ComboBox的获取

if (StringTools.ObjectToInt(searchCmbConsumeMarket.SelectedIndex) != 0)
{
DataBindControlsImplement.ComboBoxItemTextValue comboItem =
(DataBindControlsImplement.ComboBoxItemTextValue)this.searchCmbConsumeProject.SelectedIte
m;
string selectedText = comboItem.selectText;
int selectedValue = comboItem.selectValue;
}

相关文档
最新文档