473,722 Members | 2,285 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ComboBox in DataGrid,

I want to implement a key hit with enter to dropdown a combobox that is in
the datagrid. in this case I need to override its original behaviours. I
found some codes from the web. Does anyone know how to use this code? please
help!

http://www.experts-exchange.com/Prog..._20862953.html


using System;
using System.Windows. Forms;
using System.Drawing;
using System.Data;
using System.Collecti ons;
using System.Diagnost ics;
using System.Reflecti on;

namespace AdvancedDataGri d
{
/// <summary>
/// Implementation of a ComboBox as a column in a DataGrid
/// </summary>
public class DataGridDataBou ndComboBoxColum n : DataGridTextBox Column
{
private ComboBox internalComboBo x = new ComboBox();
private bool currentlyInEdit = false;
private CurrencyManager source = null;
private int rowNum = -1;
private AdvancedDataGri d.MyDataGrid dataGrid = null;

#region Properties
private object nullValue = DBNull.Value;
/// <summary>
/// Gives a value that will be considered null and will be replaced for
showing by NullValue
/// </summary>
public object NullValue
{
set {this.nullValue = value;}
get {return this.nullValue; }
}

private object nullCorrespondi ngValue = null;
/// <summary>
/// Gives a value that will replace the null values (given by NullValue)
for showing
/// </summary>
public object NullCorrespondi ngValue
{
set {this.nullCorre spondingValue = value;}
get {return this.nullCorres pondingValue;}
}

public object DataSource
{
set
{
// If the display member or value member is wrong,
// this line will clear it
this.internalCo mboBox.DataSour ce = value;
SetComboBoxDrop DownWidth();
}
get { return this.internalCo mboBox.DataSour ce; }
}
public string DisplayMember
{
set
{
this.internalCo mboBox.DisplayM ember = value;
SetComboBoxDrop DownWidth();
}
get { return this.internalCo mboBox.DisplayM ember; }
}
public string ValueMember
{
set {this.internalC omboBox.ValueMe mber = value; }
get { return this.internalCo mboBox.ValueMem ber; }
}
#endregion

#region Construction
public DataGridDataBou ndComboBoxColum n () : base()
{
this.internalCo mboBox.Visible = false;
this.internalCo mboBox.DropDown Style = ComboBoxStyle.D ropDownList;
// Some events that guarantee correct working
this.internalCo mboBox.LostFocu s += new EventHandler
(OnInternalComb oBoxLostFocus);
}
#endregion

#region Event handlers for the combo box
private void OnInternalCombo BoxLostFocus (object sender, EventArgs e)
{
if ((sender is DataGrid && !this.internalC omboBox.Focused ) ||
sender == this.internalCo mboBox)
{
if (this.currently InEdit)
Commit (this.source, this.rowNum);
}
}
#endregion

#region Key management
/// <summary>
/// Handles opening and closing of the ComboBox with the keyboard
/// For this function to work, the data grid should be of type
AdvancedDataGri d
/// </summary>
/// <param name="msg"></param>
/// <param name="keyData"> </param>
/// <returns></returns>
public bool ProcessCmdKey(r ef Message msg, Keys keyData)
{
if (!this.currentl yInEdit)
return false;

if (keyData == Keys.Down)
{
// Try to select next or the first item
if (this.internalC omboBox.Selecte dIndex <
this.internalCo mboBox.Items.Co unt - 1)
this.internalCo mboBox.Selected Index++;
else if (this.internalC omboBox.Items.C ount > 0)
this.internalCo mboBox.Selected Index = 0;
return true;
}
else if (keyData == Keys.Up)
{
// Try to select previous or the last item
if (this.internalC omboBox.Selecte dIndex > 0)
this.internalCo mboBox.Selected Index--;
else if (this.internalC omboBox.Items.C ount > 0)
this.internalCo mboBox.Selected Index =
this.internalCo mboBox.Items.Co unt - 1;
return true;
}
else if ((keyData == (Keys.Up | Keys.Alt) ||
keyData == (Keys.Down | Keys.Alt)) &&
!this.internalC omboBox.Dropped Down)
{
this.internalCo mboBox.DroppedD own = true;
return true;
}
// Keys.Down | Keys.Alt work automatically if DropedDown
else if ((keyData == Keys.Enter || keyData == (Keys.Up | Keys.Alt)) &&
this.internalCo mboBox.DroppedD own)
{
HideDropDown();
return true;
}
else if (keyData == Keys.Escape)
{
Abort (this.rowNum);
return true;
}

return false;
}
#endregion

#region Overriden methods

protected override object GetColumnValueA tRow (CurrencyManage r source, int
rowNum)
{
object val = base.GetColumnV alueAtRow (source, rowNum);
// Check for the null value
if (Object.Equals (val, this.NullValue) && this.NullCorres pondingValue !=
null)
val = this.NullCorres pondingValue;

foreach (object o in this.internalCo mboBox.Items)
{
object oVal = GetValueMember (o);
if ((oVal == null && val == null) ||
(oVal != null && oVal.Equals (val)))
return GetDisplayMembe r (o);
}
return DBNull.Value;
}

protected override void Abort(int rowNum)
{
// If in read only mode, just follow the basic methods
if (this.DataGridT ableStyle.DataG rid.ReadOnly || this.ReadOnly ||
(this.DataGridT ableStyle.DataG rid.DataSource is DataView &&
!((DataView)thi s.DataGridTable Style.DataGrid. DataSource).All owEdit))
{
base.Abort (rowNum);
return;
}

if(this.current lyInEdit)
{
this.currentlyI nEdit = false;
this.source = null;
this.rowNum = -1;
this.internalCo mboBox.Hide();
if (this.internalC omboBox.Dropped Down)
HideDropDown();
}
}

protected override bool Commit(Currency Manager dataSource,int rowNum)
{
// If in read only mode, just follow the basic methods
if (this.DataGridT ableStyle.DataG rid.ReadOnly || this.ReadOnly ||
(this.DataGridT ableStyle.DataG rid.DataSource is DataView &&
!((DataView)thi s.DataGridTable Style.DataGrid. DataSource).All owEdit))
return base.Commit(dat aSource, rowNum);

if(this.current lyInEdit)
{
object selValue = this.internalCo mboBox.Selected Value;
if (selValue == null || Object.Equals (selValue,
this.NullCorres pondingValue))
selValue = this.NullValue;
SetColumnValueA tRow(dataSource , rowNum, selValue);

this.currentlyI nEdit = false;
this.source = null;
this.rowNum = -1;
this.internalCo mboBox.Hide();
if (this.internalC omboBox.Dropped Down)
HideDropDown();
}

return true;
}

protected override void Edit(CurrencyMa nager source, int rowNum, Rectangle
bounds, bool readOnly, string instantText, bool cellIsVisible)
{
// If in read only mode, just follow the basic methods
if (this.DataGridT ableStyle.DataG rid.ReadOnly || this.ReadOnly ||
(this.DataGridT ableStyle.DataG rid.DataSource is DataView &&
!((DataView)thi s.DataGridTable Style.DataGrid. DataSource).All owEdit))
{
base.Edit(sourc e, rowNum, bounds, readOnly, instantText, cellIsVisible);
return;
}

if (this.currently InEdit)
return;

if(!cellIsVisib le)
return;

// Important: show it before setting the selected value
// otherwise in some cases the value from the previous edit is returned
// (when the drop down is open with the mouse, a new value is pointed
// and Tab is pressed)
this.internalCo mboBox.Bounds = bounds;
this.internalCo mboBox.Show();

// Get the underlying value
// The current implementation of GetColumnValueA tRow will return the
DisplayMember
object val = base.GetColumnV alueAtRow (source, rowNum);
// Check for the null value
if (Object.Equals (val, this.NullValue) && this.NullCorres pondingValue !=
null)
val = this.NullCorres pondingValue;

if (val == null || val == DBNull.Value)
if (this.internalC omboBox.Items.C ount > 0)
this.internalCo mboBox.Selected Index = 0;
else
this.internalCo mboBox.Selected Index = -1;
else
this.internalCo mboBox.Selected Value = val;

this.currentlyI nEdit = true;
this.source = source;
this.rowNum = rowNum;

ColumnStartedEd iting (this.internalC omboBox);
}

protected override int GetMinimumHeigh t()
{
return this.internalCo mboBox.Preferre dHeight + 1;
}

protected override void SetDataGridInCo lumn(DataGrid value)
{
base.SetDataGri dInColumn (value);

if (value == this.dataGrid)
return;

Debug.Assert (value != null);
Debug.Assert (value is AdvancedDataGri d.MyDataGrid,"T he used data grid
should be of type AdvancedDataGri d");

if (this.dataGrid != null)
{
this.dataGrid.C ontrols.Remove (this.internalC omboBox);
this.dataGrid.L ostFocus -= new EventHandler
(OnInternalComb oBoxLostFocus);
}

this.dataGrid = (AdvancedDataGr id.MyDataGrid)v alue;

this.dataGrid.C ontrols.Add(thi s.internalCombo Box);
// Some events that guarantee correct working
this.dataGrid.L ostFocus += new EventHandler
(OnInternalComb oBoxLostFocus);
}
#endregion

#region Helper functions
private void HideDropDown()
{
// Unknown why, the value is lost when DroppedDown is set to false
object val = this.internalCo mboBox.Selected Value;
this.internalCo mboBox.DroppedD own = false;
this.internalCo mboBox.Selected Value = val;
}
private object GetMember (object o, string member)
{
DataRow row = null;
if (o is DataRowView)
row = ((DataRowView)o ).Row;
if (o is DataRow)
row = (DataRow)o;
if (row != null)
{
object ret = row[member];
if (ret == null)
return DBNull.Value;
else
return ret;
}
else
{
PropertyInfo pi = o.GetType().Get Property (member);
Debug.Assert (pi != null);
return pi.GetValue (o, null);
}
}

private string GetDisplayMembe r (object o)
{
if (o == null || o == DBNull.Value)
return this.NullText;
object val = GetMember (o, this.internalCo mboBox.DisplayM ember);
if (val == null || val == DBNull.Value)
return this.NullText;
else
return val.ToString();
}

private object GetValueMember (object o)
{
return GetMember (o, this.internalCo mboBox.ValueMem ber);
}

/// <summary>
/// Sets the DropDownWidth property of the combo box if all needed
/// properties are already set
/// </summary>
private void SetComboBoxDrop DownWidth()
{
if (this.internalC omboBox.DataSou rce == null ||
this.internalCo mboBox.DisplayM ember == null ||
this.internalCo mboBox.DisplayM ember == String.Empty)
return;

Graphics g = this.internalCo mboBox.CreateGr aphics ();
float w = 0;
foreach (object o in this.internalCo mboBox.Items)
w = Math.Max (w, g.MeasureString (GetDisplayMemb er (o),
this.internalCo mboBox.Font).Wi dth);
if (w > 0)
this.internalCo mboBox.DropDown Width = (int)(w + 0.5);
}
#endregion
}
}
Nov 16 '05 #1
2 4329
What exactly is your question? Do you want to know how to integrate this
code into your own application so that you can have a combo box in a grid or
does your question have to do with using the enter key to activate the
dropdown? Or is your question as you ask it: Do you want to know if we know
how to use that code? I doubt that's really your question.

If you can be more specific about your question, you're more likely to get a
response.

Pete
"pei_world" <pe*******@hotm ail.com> wrote in message
news:ev******** ******@TK2MSFTN GP14.phx.gbl...
I want to implement a key hit with enter to dropdown a combobox that is in
the datagrid. in this case I need to override its original behaviours. I
found some codes from the web. Does anyone know how to use this code? please help!

[snip]
Nov 16 '05 #2
sorry about my question, I have integrated a combobox into the datagrid. But
when I try to use keyboard to control the datagrid, after I press the Enter
key, combobox dropped down, however, when I try to select the next item on
the combobox, it move to the next row of the datagrid. how can I use this
code to override its default action.
what I try to do are:
1.press Enter key to show Combobox Dropdown list
2.Press UP or Down key to select item
3.Press Enter key to hide Dropdown list

Also, How to use this code in my application? I am using other code to
integrate combobox into datagrid.
"Pete Davis" <pd******@NOSPA M.hotmail.com> wrote in message
news:F9******** ************@gi ganews.com...
What exactly is your question? Do you want to know how to integrate this
code into your own application so that you can have a combo box in a grid
or
does your question have to do with using the enter key to activate the
dropdown? Or is your question as you ask it: Do you want to know if we
know
how to use that code? I doubt that's really your question.

If you can be more specific about your question, you're more likely to get
a
response.

Pete
"pei_world" <pe*******@hotm ail.com> wrote in message
news:ev******** ******@TK2MSFTN GP14.phx.gbl...
I want to implement a key hit with enter to dropdown a combobox that is
in
the datagrid. in this case I need to override its original behaviours. I
found some codes from the web. Does anyone know how to use this code?

please
help!

[snip]

Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1412
by: Gamze | last post by:
Hi, In my vb.net windows application ,i have combobox which is populated by sqlserver database table.When i select value from combobox ,value saved in to other table of my database and i use to datagrid to show this table. Myproblem is , i want to get text value from datagrid and my combobox should select this value (Which i selected before) when i want to update values in datagrid e.g
3
4270
by: Bill C. | last post by:
Hello, I know this has been discussed a lot already because I've been searching around for information the last few weeks. I'm trying to implement a DataGridComboBoxColumn class. I've found several examples on the web. They all seem to have problems, though that I've been unable to resolve. The most promising example I have found is at:
2
2386
by: john sutor | last post by:
Does anyone know how to create a combobox in a standard datagrid? I can create check boxes , but not the combobox
3
3027
by: PeterZ | last post by:
G'day, After doing much searching and pinching bits of ideas from here there and everywhere I came up with a fairly 'clean' solution of including a comboBox into a dataGrid column. You can download a fully working C# sample with the Northwind.mdb here: www.insightgis.com.au/web/stuff/DataGridCombo.zip
3
6831
by: TT (Tom Tempelaere) | last post by:
Hay there, I'm writing my own DataGridComboBoxColumn because .NET 1.1 does not have one (I hope .NET 2.0 supplies one). I based it on this article: http://msdn.microsoft.com/msdnmag/issues/03/08/DataGrids/default.aspx I have a problem when there are two DataGrid's on one form, and when I switch focus from one grid to the other. To be more precise, when I'm editing a combo box column in one grid, and then click in the combo column of...
1
1470
by: John Doe | last post by:
Now i know how to manually add a combobox to a datagrid, but how would i handle the recordset below? ID | FirstName | LastName | Job -------------------------------- 1 |Joe | Smith | janitor 1 |Joe | Smith | cashier 2 |Bob | Anderson | cook I want to bind the above datatable to a datagrid so that
0
407
by: dbuchanan | last post by:
ComboBox databindng Problem == How the ComboBox is setup and used: My comboBox is populated by a lookup table. The ValueMember is the lookup table's Id and the DisplayMember is the text from a corresponding field in the lookup table. In my data table we store the ID in what I will call the 'key' field. == Description of the desired operation:
1
2098
by: fiaolle | last post by:
Hi The first set of source code is the class for a combobox in a grid, hopefully. In the second set of code we try to use the combobox class, but the grid is empty. I don't understand how this works. The first set of code I downloaded from internet and when i tried it, it worked fine. But when I changed the second part of the code it started to give me trouble. Before I changed the code they used Datacolumns,Datarows and Datatables and...
4
1817
by: JJGarcia | last post by:
Hi Everyone, I'll try to explain the process I'm following, I'm new to this so I'm triying the easy way first, probably the lasyest too! I created a new Project, drag in to it a SQLConnection, configured, dragged an Dataadapter per each table I need it, then generated the dataset, after that, I stablished the relations between tables, then, went over to the datasources, choose the parent datasource and clicked on the + sign, it...
0
8860
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9376
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9234
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9086
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6678
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5994
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2599
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2146
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.