Checked Dropdownlist in a DataGridView

288 views
Skip to first unread message

Aravindh Kathir

unread,
Apr 20, 2009, 2:56:20 AM4/20/09
to DotNetDe...@googlegroups.com
Hi,
 
      I am Developing a Windows Application in VB.NET. In Which one of the Windows Form will Display data in DataGridView Control. I Need a Checked DropDownList Column in DataGridView.
 
For this process i have Created a Custom Control (Checked DropDownList Control), But if i add that control in to the
DataGridview Control i am unable to access that control in Datagridview both inGUI and Code.
The Following are code, please point out the problem that i have done..
 
/ *------------------------------------------------------   Code Starts Here ---------------------------------------------------------------------------------------------- * /
 

using

System;

using

System.Collections.Generic;

using

System.Text;

using

System.Windows.Forms;

using

System.Collections;

using

System.Drawing;

namespace

dgdCheckedListBox

{

public class CheckedListBoxColumn : DataGridViewColumn

{

public CheckedListBoxColumn()

:

base(new CheckedListBoxCell())

{

}

public override DataGridViewCell CellTemplate

{

get

{

return base.CellTemplate;

}

set

{

if (value != null &&

!

value.GetType().IsAssignableFrom(typeof(CheckedListBoxCell)))

{

throw new InvalidCastException("Must be a CheckedListBoxCell");

}

base.CellTemplate = value;

}

}

}

public class CheckedListBoxCell : DataGridViewCell

{

public CheckedListBoxCell()

:

base()

{

}

public override void InitializeEditingControl(int rowIndex, object

initialFormattedValue,

DataGridViewCellStyle dataGridViewCellStyle)

{

// Set the value of the editing control to the current cell value.

base.InitializeEditingControl(rowIndex, initialFormattedValue,

dataGridViewCellStyle);

CheckedListBoxEditingControl ctl =

DataGridView.EditingControl

as CheckedListBoxEditingControl;

InitializeCheckedListBox(ctl, (

ICollection)this.FormattedValue);

}

private void InitializeCheckedListBox(CheckedListBox ctrl, ICollection value)

{

ctrl.Items.Clear();

foreach (object obj in value)

{

ctrl.Items.Add(obj.ToString());

}

ctrl.Tag =

this.Value;

}

public override Type EditType

{

get

{

return typeof(CheckedListBoxEditingControl);

}

}

protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)

{

if (value == null)

{

return new List<object>();

}

return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);

}

public override Type FormattedValueType

{

get

{

return typeof(ICollection);

}

}

public override Type ValueType

{

get

{

return typeof(ICollection);

}

}

public CheckedListBox internalControl;

//private ComboBox lst = new ComboBox();

private CheckComboBoxTest.CheckedComboBox chkdrop = new CheckComboBoxTest.CheckedComboBox();

protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)

{

base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

graphics.FillRectangle(

new SolidBrush(cellStyle.BackColor), cellBounds);

if (internalControl == null)

{

internalControl =

new CheckedListBox();

}

internalControl.Items.Clear();

chkdrop.Items.Clear();

ICollection collection = value as ICollection;

//if (collection != null)

{

//foreach (object obj in collection)

{

internalControl.Items.Add(

"obj",true );

internalControl.Items.Add(

"obj1");

chkdrop.Items.Add(

"hi",true);

chkdrop.Items.Add(

"hi1",true);

//chkdrop.DroppedDown = true;

//lst.Items.Add("Hisdfsdf");

//lst.Items.Add("ghjgjhg");

}

{

}

Bitmap bmp = new Bitmap(cellBounds.Width, cellBounds.Height);

//internalControl.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));

chkdrop.DrawToBitmap(bmp,

new Rectangle(0, 0, bmp.Width, bmp.Height));

//lst.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));

graphics.DrawImage(bmp, cellBounds,

new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);

}

}

protected override void OnClick(DataGridViewCellEventArgs e)

{

//base.DataGridView.BeginEdit(false);

//base.OnClick(e);

}

}

class CheckedListBoxEditingControl : CheckedListBox, IDataGridViewEditingControl

{

DataGridView dataGridView;

private bool valueChanged = false;

int rowIndex;

public CheckedListBoxEditingControl()

{

}

// Implements the IDataGridViewEditingControl.EditingControlFormattedValue

// property.

public object EditingControlFormattedValue

{

get

{

return this.Tag;

}

set

{

// this.Tag = value;

}

}

// Implements the

// IDataGridViewEditingControl.GetEditingControlFormattedValue method.

public object GetEditingControlFormattedValue(

DataGridViewDataErrorContexts context)

{

return EditingControlFormattedValue;

}

// Implements the

// IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.

public void ApplyCellStyleToEditingControl(

DataGridViewCellStyle dataGridViewCellStyle)

{

this.Font = dataGridViewCellStyle.Font;

this.ForeColor = dataGridViewCellStyle.ForeColor;

this.BackColor = dataGridViewCellStyle.BackColor;

}

// Implements the IDataGridViewEditingControl.EditingControlRowIndex

// property.

public int EditingControlRowIndex

{

get

{

return rowIndex;

}

set

{

rowIndex =

value;

}

}

// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey

// method.

public bool EditingControlWantsInputKey(

Keys key, bool dataGridViewWantsInputKey)

{

// Let the DateTimePicker handle the keys listed.

switch (key & Keys.KeyCode)

{

case Keys.Left:

case Keys.Up:

case Keys.Down:

case Keys.Right:

case Keys.Home:

case Keys.End:

case Keys.PageDown:

case Keys.PageUp:

return true;

default:

return !dataGridViewWantsInputKey;

}

}

// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit

// method.

public void PrepareEditingControlForEdit(bool selectAll)

{

// No preparation needs to be done.

}

// Implements the IDataGridViewEditingControl

// .RepositionEditingControlOnValueChange property.

public bool RepositionEditingControlOnValueChange

{

get

{

return false;

}

}

// Implements the IDataGridViewEditingControl

// .EditingControlDataGridView property.

public DataGridView EditingControlDataGridView

{

get

{

return dataGridView;

}

set

{

dataGridView =

value;

}

}

// Implements the IDataGridViewEditingControl

// .EditingControlValueChanged property.

public bool EditingControlValueChanged

{

get

{

return valueChanged;

}

set

{

valueChanged =

value;

}

}

// Implements the IDataGridViewEditingControl

// .EditingPanelCursor property.

public Cursor EditingPanelCursor

{

get

{

return base.Cursor;

}

}

}

}

 

/ *------------------------------------------------------   Code Ends Here ---------------------------------------------------------------------------------------------- * /
 
 
 
 
Thanks
 
Regards
Aravindh.K

vinayas

unread,
May 4, 2009, 8:47:11 AM5/4/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting

hi aravindh...i am facing same problem...
if u have got any solution please let me know.

I have added it on form and trying to initiatize it.but it fails at
GetFormattedValue function. it throws exception in its return
statement. FormatException.


On Apr 20, 11:56 am, Aravindh Kathir <aravind...@gmail.com> wrote:
> Hi,
>
>       I am Developing a Windows Application in VB.NET. In Which one of the
> Windows Form will Display data in DataGridView Control. I Need a Checked
> DropDownList Column in DataGridView.
>
> For this process i have Created a Custom Control (Checked DropDownList
> Control), But if i add that control in to the
> DataGridview Control i am unable to access that control in Datagridview both
> inGUI and Code.
> The Following are code, please point out the problem that i have done..
>
> / *------------------------------------------------------   Code Starts
> Here ---------------------------------------------------------------------------­-------------------
> graphics.FillRectangle(new SolidBrush(cellStyle.BackColor), cellBounds);
> Here ---------------------------------------------------------------------------­-------------------

Aravindh Kathir

unread,
May 5, 2009, 1:58:52 AM5/5/09
to DotNetDe...@googlegroups.com
Hi ,

Finally i solved this issue, the following is the sample code...

/************************* Code Begins Here ****************************************/

Imports System
Imports System.Windows.Forms
Imports CheckComboBoxTest
Imports System.Data.SqlClient


Public Class CheckedDropDownColumn
    Inherits DataGridViewColumn

    Public Sub New()
        MyBase.New(New CheckedDropDownCell())
    End Sub

    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(ByVal value As DataGridViewCell)

            ' Ensure that the cell used for the template is a CheckedDropDownCell.
            If (value IsNot Nothing) AndAlso _
                Not value.GetType().IsAssignableFrom(GetType(CheckedDropDownCell)) _
                Then
                Throw New InvalidCastException("Must be a CheckedDropDownListColumn")
            End If
            MyBase.CellTemplate = value

        End Set
    End Property

    Private Sub InitializeComponent()

    End Sub
End Class

Public Class CheckedDropDownCell
    Inherits DataGridViewTextBoxCell
    Private c As ICollection
    Public Sub New()
    End Sub

    Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
        ByVal initialFormattedValue As Object, _
        ByVal dataGridViewCellStyle As DataGridViewCellStyle)

        ' Set the value of the editing control to the current cell value.
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
            dataGridViewCellStyle)

        'Dim ctl As CheckedDropDownEditingControl = CType(DataGridView.EditingControl, CheckedDropDownEditingControl)
        'Dim cultureinfo As New Globalization.CultureInfo("en-GB", True)
        'ctl.Value = Convert.ToDateTime(DateTime.Today.Day().ToString + "/" + DateTime.Today.Month().ToString + "/" + DateTime.Today.Year().ToString + " 00:00:00", cultureinfo.DateTimeFormat)
        'ctl.Value = DateTime.Parse(Me.Value, System.Globalization.CultureInfo.CreateSpecificCulture("en-AU").DateTimeFormat)
        'ctl.Value = CType(Me.Value, DateTime)

        'If Flag = 2 Then
        '    ctl.MinDate = Today.Date
        '    ctl.MaxDate = DateAdd(DateInterval.Day, 30, ctl.Value)
        'End If
        ''If Flag = 1 Then
        ''    'ctl.MinDate = DateAdd(DateInterval.Day, 2, ctl.Value)
        ''    ctl.MaxDate = Today.Date
        ''End If
        'ctl.MaxDate = DateAdd(30)
        
        Dim ctl As CheckedDropDownEditingControl = CType(DataGridView.EditingControl, CheckedDropDownEditingControl)
        Using con As New SqlConnection(glbSqlCon.ConnectionString)
            Dim cmd As New SqlCommand("Select Attendance_Nature from Nature_of_Attendance where NatureFlag = 0 order by Attendance_Nature", con)
            Dim dr As SqlDataReader
            con.Open()
            dr = cmd.ExecuteReader()
            Dim arr As New ArrayList()
            If dr.HasRows Then
                While dr.Read()
                    arr.Add(dr.GetString(0))
                End While
            End If
            con.Close()
            Dim dd As ICollection
            dd = arr
            Data(dd)
        End Using
        InitializeValue(ctl, c)

    End Sub
    Public Sub InitializeValue(ByVal ctl As CheckedDropDownEditingControl, ByVal c As ICollection)
        Try
            If c IsNot Nothing Then
                ctl.Items.Clear()
                For Each var As Object In c
                    ctl.Items.Add(var)
                Next
            End If
        Catch ex As Exception
            ex.ToString()
        End Try
    End Sub
    Public Sub Data(ByVal c1 As ICollection)
        c = c1
    End Sub
    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing contol that CheckedDropDownCell uses.
            Return GetType(CheckedDropDownEditingControl)
        End Get
    End Property

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that CheckedDropDownCell contains.
            Return GetType([String])
        End Get
    End Property

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            Return ""
        End Get
    End Property

End Class

Public Class CheckedDropDownEditingControl
    Inherits CheckedComboBox
    Implements IDataGridViewEditingControl

    Private dataGridViewControl As DataGridView
    Private valueIsChanged As Boolean = False
    Private rowIndexNum As Integer

    Public Sub New()

    End Sub

    Public Property EditingControlFormattedValue() As Object _
        Implements IDataGridViewEditingControl.EditingControlFormattedValue
        Get
            Return Me.Text
        End Get
        Set(ByVal value As Object)
            If TypeOf value Is String Then
                Me.Text = DirectCast(value, [String])
            End If
        End Set
    End Property

    Public Function GetEditingControlFormattedValue(ByVal context _
        As DataGridViewDataErrorContexts) As Object _
        Implements IDataGridViewEditingControl.GetEditingControlFormattedValue

        Return Me.Text

    End Function

    Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As _
        DataGridViewCellStyle) _
        Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl

        Me.Font = dataGridViewCellStyle.Font
    End Sub

    Public Property EditingControlRowIndex() As Integer _
        Implements IDataGridViewEditingControl.EditingControlRowIndex
        Get
            Return rowIndexNum
        End Get
        Set(ByVal value As Integer)
            rowIndexNum = value
        End Set
    End Property

    Public Function EditingControlWantsInputKey(ByVal key As Keys, _
        ByVal dataGridViewWantsInputKey As Boolean) As Boolean _
        Implements IDataGridViewEditingControl.EditingControlWantsInputKey

        ' Let the CheckedDropDownList handle the keys listed.
        Select Case key And Keys.KeyCode
            Case Keys.Left, Keys.Up, Keys.Down, Keys.Right, _
                Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp

                Return True

            Case Else
                Return Not dataGridViewWantsInputKey
        End Select

    End Function

    Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _
        Implements IDataGridViewEditingControl.PrepareEditingControlForEdit

        ' No preparation needs to be done.

    End Sub

    Public ReadOnly Property RepositionEditingControlOnValueChange() _
        As Boolean Implements _
        IDataGridViewEditingControl.RepositionEditingControlOnValueChange

        Get
            Return False
        End Get

    End Property

    Public Property EditingControlDataGridView() As DataGridView _
        Implements IDataGridViewEditingControl.EditingControlDataGridView

        Get
            Return dataGridViewControl
        End Get
        Set(ByVal value As DataGridView)
            dataGridViewControl = value
        End Set

    End Property

    Public Property EditingControlValueChanged() As Boolean _
        Implements IDataGridViewEditingControl.EditingControlValueChanged

        Get
            Return valueIsChanged
        End Get
        Set(ByVal value As Boolean)
            valueIsChanged = value
        End Set

    End Property

    Public ReadOnly Property EditingControlCursor() As Cursor _
        Implements IDataGridViewEditingControl.EditingPanelCursor

        Get
            Return MyBase.Cursor
        End Get

    End Property
    Protected Overloads Overrides Sub OnTextChanged(ByVal e As EventArgs)
        'valueChanged = True
        Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
        MyBase.OnTextChanged(e)
    End Sub
End Class
/******************************** Code Ends Here ******************************************/

I hope this will help to get rid of that problem..

Regards,
Aravindh.K
Reply all
Reply to author
Forward
0 new messages