Locations of visitors to this page
Onteora Software - August 2006

Onteora Software

Ken Tucker's Blog

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Predicates

Predicates



I recently read an article in the MSDN magazine about Predicates and Actions written by Ken Getz. I was thinking that predicates will make it easy to create a master details datagridview for a business object. This example creates 2 classes Customers and Orders. I used the Northwind database to fill a list of customers and a list of orders. I bound one grid to a binding source who's datasource is the list of customers. In the binding sources position changed event I use the list of orders findall method to show all the orders for a customer.





The classes

Public Class Orders
    Private mintOrderID As Integer
    Public Property OrderID() As Integer
        Get
            Return mintOrderID
        End Get
        Set(ByVal value As Integer)
            mintOrderID = value
        End Set
    End Property

    Private mdtOrderDate As Date
    Public Property OrderDate() As Date
        Get
            Return mdtOrderDate
        End Get
        Set(ByVal value As Date)
            mdtOrderDate = value
        End Set
    End Property

    Private mstrCustID As String
    Public Property CustomerID() As String
        Get
            Return mstrCustID
        End Get
        Set(ByVal value As String)
            mstrCustID = value
        End Set
    End Property


End Class


Public Class Customers
    Private mstrCustID As String
    Public Property CustomerID() As String
        Get
            Return mstrCustID
        End Get
        Set(ByVal value As String)
            mstrCustID = value
        End Set
    End Property

    Private mstrCompanyName As String
    Public Property CompanyName() As String
        Get
            Return mstrCompanyName
        End Get
        Set(ByVal value As String)
            mstrCompanyName = value
        End Set
    End Property

    Private mstrContactName As String
    Public Property ContactName() As String
        Get
            Return mstrContactName
        End Get
        Set(ByVal value As String)
            mstrContactName = value
        End Set
    End Property


End Class



 

The Main code

Imports System.Data.SqlClient

Public Class Form1
    Dim lstCustomers As New List(Of Customers)
    Dim lstOrders As New List(Of Orders)
    Dim WithEvents bsCustomers As New BindingSource
    Private CustId As String = ""

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FillCustomers()
        FillOrders()
        bsCustomers.DataSource = lstCustomers
        DataGridView1.DataSource = bsCustomers
    End Sub

    Private Sub FillCustomers()
        Dim conn As SqlConnection
        Dim strConn As String
        Dim dr As SqlDataReader
        Dim cmd As SqlCommand
        Dim strSql As String

        strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;"

        conn = New SqlConnection(strConn)

        conn.Open()

        strSql = "Select CustomerID, CompanyName, ContactName from Customers"


        cmd = New SqlCommand(strSql, conn)

        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

        Do While dr.Read
            Dim cls As New Customers
            With cls
                .CompanyName = dr("CompanyName").ToString
                .ContactName = dr("ContactName").ToString
                .CustomerID = dr("CustomerID").ToString
            End With
            lstCustomers.Add(cls)
        Loop
        conn.Close()

    End Sub

    Private Sub FillOrders()
        Dim conn As SqlConnection
        Dim strConn As String
        Dim dr As SqlDataReader
        Dim cmd As SqlCommand
        Dim strSql As String

        strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;"

        conn = New SqlConnection(strConn)

        conn.Open()

        strSql = "Select CustomerID, OrderID, OrderDate from Orders"


        cmd = New SqlCommand(strSql, conn)

        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

        Do While dr.Read
            Dim cls As New Orders
            With cls
                .OrderID = dr.GetInt32(1)
                .OrderDate = dr.GetDateTime(2)
                .CustomerID = dr("CustomerID").ToString
            End With
            lstOrders.Add(cls)
        Loop
        conn.Close()

    End Sub

    Private Function FindCustomerOrders(ByVal Ordr As Orders) As Boolean
        Return Ordr.CustomerID = CustId
    End Function

    Private Sub bsCustomers_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles bsCustomers.PositionChanged
        Dim cust As Customers

        cust = TryCast(bsCustomers.Current, Customers)
        If Not cust Is Nothing Then
            CustId = cust.CustomerID
            DataGridView2.DataSource = lstOrders.FindAll(AddressOf FindCustomerOrders)
        End If
    End Sub
End Class

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | VB | Generics
Posted by Ken Tucker on Wednesday, August 30, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Secure Strings

Secure Strings



The SecureString is a new class that was added in the .Net framework 2.0 which allows you to store info in memory securely. The SecureString could be used to safely secure a password or credit number. The example shows how to add info to the string, prevent changes from being make to the data, and finally how to get the info back. I included c# and VB samples.





C# sample

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.Runtime.InteropServices;

namespace SecureStringCS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //
            // How to add to a secure string
            //
            SecureString ss = new SecureString();
            foreach (Char c in "This is some info I need to keep secure".ToCharArray())
            {
                ss.AppendChar(c);
            }
            //
            // Prevent changes
            //
            ss.MakeReadOnly();

            //
            // How to get the info back
            //

            IntPtr ptr;
            ptr=Marshal.SecureStringToBSTR(ss);

            String s;
            s = Marshal.PtrToStringAuto(ptr);
            Marshal.ZeroFreeBSTR(ptr);

        }
    }
}

VB sample

Imports System.Security
Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        '
        ' how to add to a secure string
        '
        Dim ss As New SecureString
        For Each c As Char In "This is some info I need to keep secure".ToCharArray
            ss.AppendChar(c)
        Next

        ' prevent changes

        ss.MakeReadOnly()

        '
        ' how to get the info back
        '
        Dim ptr As IntPtr
        ptr = Marshal.SecureStringToBSTR(ss)
        Dim s As String

        s = Marshal.PtrToStringAuto(ptr)
        Marshal.ZeroFreeBSTR(ptr)

    End Sub
End Class

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General | VB | C#
Posted by Ken Tucker on Tuesday, August 29, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Create a Pivot Table

Create a Pivot Table



Here is a quick example on how to rotate or pivot the data in a datagridview. This is a c# program which creates a new data table with a rotated version of the data to bind to. There is a VB version on the vb-tips website.





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Pivot
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable dt1;

        private void Form1_Load(object sender, EventArgs e)
        {
            dt1 = CreateTable();
            DataTable dt2 = new DataTable("Reflected");
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                dt2.Columns.Add(i.ToString());
            }

            for (int x = 0; x < dt1.Columns.Count; x++)
            {
                DataRow dr = dt2.NewRow();
                for (int y = 0; y < dt1.Rows.Count; y++)
                {
                    dr[y] = dt1.Rows[y][x];
                }
                dt2.Rows.Add(dr);
            }

            dataGridView1.RowHeadersWidth = 60;
            dataGridView1.DataSource = dt2;
            dataGridView1.AllowUserToAddRows = false;
        }

        public DataTable CreateTable()
        {
            DataTable dt = new DataTable("Orginal");
            dt.Columns.Add("Name");
            dt.Columns.Add("State");
            dt.Columns.Add("Country");

            Object[] arRow = new Object[3];
            arRow[0] = "Ken";
            arRow[1]="Florida";
            arRow[2] = "US";

            dt.LoadDataRow(arRow,true);

            arRow[0] = "Cor";
            arRow[1] = "Holland";
            arRow[2] = "EU";

            dt.LoadDataRow(arRow, true);
            return dt;
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == -1 && e.RowIndex >= 0)
            {
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                e.PaintBackground(e.ClipBounds, true);
                e.Graphics.DrawString(dt1.Columns[e.RowIndex].ColumnName.ToString(), this.Font, Brushes.Black, e.CellBounds, sf );
                e.Handled = true;
            }
        }

    }


}

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | C#
Posted by Ken Tucker on Sunday, August 27, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Extend the Table Adapter

Extend the Table Adapter



The table adapter is missing some events and properties that the data adapter has. Fortunately the tableadapter class is a partial class that uses a data adapter. This makes it easy to add properties or events to it. For this example I opened the data sources window and created a data source to the Adventure Works Employees table. I dropped the table on a form. The dataset is named AdventureWorksDataSet and the table adapter is EmployeeTableAdapter. The table adapter is in the DataSetNameTableAdapters name space. For our example it is AdventureWorksDataSetTableAdapters. The table adapter class has a variable _adapter which is the data adapter the table adapter uses for updating data.





Public Class Form1

    Private Sub EmployeeBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EmployeeBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.EmployeeBindingSource.EndEdit()
        Me.EmployeeTableAdapter.Update(Me.AdventureWorksDataSet.Employee)

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'AdventureWorksDataSet.Employee' table. You can move, or remove it, as needed.
        Me.EmployeeTableAdapter.Fill(Me.AdventureWorksDataSet.Employee)
    End Sub

    Private Sub EmployeeTableAdapter_FillError(ByVal sender As Object, ByVal e As System.Data.FillErrorEventArgs) Handles EmployeeTableAdapter.FillError

    End Sub
End Class


Namespace AdventureWorksDataSetTableAdapters
    Partial Public Class EmployeeTableAdapter
        Public Event FillError(ByVal sender As Object, ByVal e As FillErrorEventArgs)

        Private Sub _adapter_FillError(ByVal sender As Object, ByVal e As System.Data.FillErrorEventArgs) Handles _adapter.FillError
            RaiseEvent FillError(sender, e)
        End Sub

        Public Property ContineUpdateOnError() As Boolean
            Get
                Return _adapter.ContinueUpdateOnError
            End Get
            Set(ByVal value As Boolean)
                _adapter.ContinueUpdateOnError = value
            End Set
        End Property

    End Class
End Namespace

 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | VB
Posted by Ken Tucker on Friday, August 25, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Use LogParser with VB.Net

Use LogParser with VB.Net



There are times I would like to get information from the log files of a website and display them on a web form or windows form. I created a simple sample which uses the logparser dll. I added a reference to logparser.dll in the program files\log parser 2.2 folder. You can download log parser here.





Imports MSUtil

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As DataTable = parseLog("select c-ip, count(c-ip) as visits from c:\W3SVC525089654\ex*.log where cs-uri-stem like '%.aspx' group by c-ip order by visits desc")
        DataGridView1.DataSource = dt
        Me.Text = dt.Rows.Count
    End Sub

    Public Function parseLog(ByVal strQuery As String) As DataTable
        Dim parser As New LogQueryClass
        Dim iisLog As New COMIISW3CInputContextClass
        Dim rsLp As ILogRecordset
        Dim rowLp As ILogRecord

        rsLp = parser.Execute(strQuery, iisLog)
        Dim dt As New DataTable("Results")
        For x As Integer = 0 To rsLp.getColumnCount - 1
            Dim dc As New DataColumn
            dc.ColumnName = rsLp.getColumnName(x)
            Select Case rsLp.getColumnType(x)
                Case 1
                    dc.DataType = Type.GetType("System.Int32")
                Case 2
                    dc.DataType = Type.GetType("System.Double")
                Case 4
                    dc.DataType = Type.GetType("System.DateTime")
                Case Else
                    dc.DataType = Type.GetType("System.String")
            End Select
            dt.Columns.Add(dc)
        Next

        While Not rsLp.atEnd
            rowLp = rsLp.getRecord
            Dim dr As DataRow = dt.NewRow
            For x As Integer = 0 To rsLp.getColumnCount - 1
                dr.Item(x) = rowLp.getValue(x)
            Next
            dt.Rows.Add(dr)
            rsLp.moveNext()
        End While
        Return dt
    End Function
End Class

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB
Posted by Ken Tucker on Thursday, August 24, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

DataGridView Grouping

DataGridView Grouping



Several people in the msdn forums have asked how to make groupings more noticable in the datagridview. Here is my solution

DatagridView grouping



Imports System.Data.SqlClient

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        Dim strConn As String
        Dim da As SqlDataAdapter
        Dim conn As SqlConnection

        strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;"
        conn = New SqlConnection(strConn)

        da = New SqlDataAdapter("Select CategoryID, ProductName, UnitPrice from Products Order By CategoryID", conn)
        da.Fill(dt)
        dt.Columns("CategoryID").DefaultValue = 6
        DataGridView1.DataSource = dt
        DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.SkyBlue
    End Sub

    Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        Try
            If e.RowIndex > 0 And e.ColumnIndex = 0 Then
                If DataGridView1.Item(0, e.RowIndex - 1).Value = e.Value Then
                    e.Value = ""
                ElseIf e.RowIndex < DataGridView1.Rows.Count - 1 Then
                    DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.SkyBlue
                End If
            End If
        Catch ex As Exception
           
        End Try
    End Sub
End Class

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | VB
Posted by Ken Tucker on Tuesday, August 22, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Make a Datagridview move to the next cell on Enter

Make a Datagridview move to the next cell on Enter



To make a datagridview move to the next column when you press the enter you need to create a new control which inherits from datagridview. In the new control override PreProcessMessage to prevent the default enter key behavior. I also created a new column which converts an enter press to a tab key. Here is a simple c# example. A VB 2005 example is available on the VB-Tips website.





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace EnterNextCell
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DGV dg = new DGV();

        private void Form1_Load(object sender, EventArgs e)
        {
            dg.Dock = DockStyle.Fill;
            this.Controls.Add(dg);
            String strConn = "Server = .;Database = NorthWind;Integrated Security = SSPI;";

            SqlConnection conn = new SqlConnection(strConn);
            SqlDataAdapter da = new SqlDataAdapter("Select LastName, Notes from Employees", conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dg.DataSource = dt;
            dg.Columns.Remove("LastName");
            dg.Columns.Remove("Notes");
            NoEnterColumn colName = new NoEnterColumn();
            colName.DataPropertyName = "LastName";

            NoEnterColumn colNotes = new NoEnterColumn();
            colNotes.DataPropertyName = "Notes";

            dg.Columns.Add(colName);
            dg.Columns.Add(colNotes);
        }
    }
}

public class DGV : DataGridView
{
    const int WM_KEYDOWN = 0x100;
    const int WM_KEYUP = 0x101;
    const int WM_CHAR = 0x0102;

    public override bool  PreProcessMessage(ref Message msg)
{
   Keys keyCode = (Keys)(int)msg.WParam & Keys.KeyCode;

   // for a datagrid, we need to eat the tab key oe else its done twice
   if((msg.Msg == WM_KEYDOWN)
    && keyCode == Keys.Enter)
   {
                int intRow = this.CurrentCell.RowIndex;
                int intCol = this.CurrentCell.ColumnIndex;
                intCol++;
                if(intCol==this.Columns.Count)
                {
                    intCol=0;
                    intRow++;
                    if(intRow==this.Rows.Count)
                    {
                        intRow=0;
                    }
       }
                this.CurrentCell = this[intCol, intRow];
                return true;
            }
            return base.PreProcessMessage(ref msg);
    }

}

public class NoEnterColumn : DataGridViewColumn
{

    public NoEnterColumn()
        :
            base(new NoEnterCell())
    {
    }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            //  Ensure that the cell used for the template is a CalendarCell.
            if ((!(value == null)
                        && !value.GetType().IsAssignableFrom(typeof(NoEnterCell))))
            {
                throw new InvalidCastException("Must be a NoEnterCell");
            }
            base.CellTemplate = value;
        }
    }
}
public class NoEnterCell : DataGridViewTextBoxCell
{

    public NoEnterCell()
    {
        //  Use the short date format.
    }

    public override Type EditType
    {
        get
        {
            //  Return the type of the editing contol that CalendarCell uses.
            return typeof(NoEnterEditingControl);
        }
    }

    public override Type ValueType
    {
        get
        {
            //  Return the type of the value that CalendarCell contains.
            return typeof(string);
        }
    }

    public override object DefaultNewRowValue
    {
        get
        {
            //  Use the current date and time as the default value.
            return "";
        }
    }

    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);
        NoEnterEditingControl ctl = ((NoEnterEditingControl)(DataGridView.EditingControl));
        ctl.Text = this.Value.ToString();
    }
}
class NoEnterEditingControl : NoEnterTB, IDataGridViewEditingControl
{

    private DataGridView dataGridViewControl;

    private bool valueIsChanged = false;

    private int rowIndexNum;

    public NoEnterEditingControl()
    {
    }

    public object EditingControlFormattedValue
    {
        get
        {
            return this.Text;
        }
        set
        {
                this.Text = value.ToString();
        }
    }

    public int EditingControlRowIndex
    {
        get
        {
            return rowIndexNum;
        }
        set
        {
            rowIndexNum = value;
        }
    }

    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }

    public DataGridView EditingControlDataGridView
    {
        get
        {
            return dataGridViewControl;
        }
        set
        {
            dataGridViewControl = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingPanelCursor property.
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }

    public bool EditingControlValueChanged
    {
        get
        {
            return valueIsChanged;
        }
        set
        {
            valueIsChanged = value;
        }
    }

    public Cursor EditingControlCursor
    {
        get
        {
            return base.Cursor;
        }
    }

    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    {
        return this.Text;
    }

    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
        this.ForeColor = dataGridViewCellStyle.ForeColor;
        this.BackColor = dataGridViewCellStyle.BackColor;
    }

    public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
    {
        //  Let the DateTimePicker handle the keys listed.
                return true;
    }

    public void PrepareEditingControlForEdit(bool selectAll)
    {
        //  No preparation needs to be done.
    }

    protected override void OnTextChanged(System.EventArgs e)
    {
        //     Notify the DataGridView that the contents of the cell have changed.
        valueIsChanged = true;
        this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        base.OnTextChanged(e);
    }
}
public class NoEnterTB : TextBox
{

    private const int WM_KEYDOWN = 256;

    private const int WM_KEYUP = 257;

    private const int WM_CHAR = 258;

    public override bool PreProcessMessage(ref System.Windows.Forms.Message msg)
    {
        Keys keyCode = (((Keys)(msg.WParam.ToInt32())) & Keys.KeyCode);
        if (((msg.Msg == WM_KEYDOWN)
                    && (keyCode == Keys.Enter)))
        {
            msg.WParam = new IntPtr((int)Keys.Tab);
        }
        return base.PreProcessMessage(ref msg);
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | C#
Posted by Ken Tucker on Wednesday, August 09, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

DatagridView ProgressBar Column

DatagridView ProgressBar Column



Here is a c# example on how to create a progress bar column for the datagridview. You can find a VB example on the VB-Tips website.





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace csProgressBarColumn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ProgressColumn col = new ProgressColumn();
            dataGridView1.Columns.Add(col);
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.RowCount = 5;
            int x = 1;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells[0].Value = x*20;
                x++;
            }

        }

    }
}

public class ProgressColumn : DataGridViewColumn
{
    public ProgressColumn():base(new ProgressCell())
    {
    }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            // Ensure that the cell used for the template is a ProgressCell.
            if (value != null &&
                !value.GetType().IsAssignableFrom(typeof(ProgressCell)))
            {
                throw new InvalidCastException("Must be a ProgressCell");
            }
            base.CellTemplate = value;
        }
    }
}

public class ProgressCell : DataGridViewImageCell
{
    protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
    {
        // Create bitmap.
        Bitmap bmp = new Bitmap(this.Size.Width, this.Size.Height);

        using (Graphics g = Graphics.FromImage(bmp))
        {
            // Percentage.
            double percentage = 0;
            double.TryParse(this.Value.ToString(), out percentage);
            string text = percentage.ToString() + " %";

            // Get width and height of text.
            Font f = new Font("Verdana", 10, FontStyle.Regular);
            int w = (int)g.MeasureString(text, f).Width;
            int h = (int)g.MeasureString(text, f).Height;

            // Draw pile.
            g.DrawRectangle(Pens.Black, 2, 2, this.Size.Width - 6 , this.Size.Height - 6);
            g.FillRectangle(Brushes.Blue, 3, 3, (float)((this.Size.Width - 6) * percentage / 100), this.Size.Height - 7);

            RectangleF rect = new RectangleF(0,0,bmp.Width,bmp.Height);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            g.DrawString(text, f, Brushes.Red, rect, sf);
        }

        return bmp;
    }


}

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | C#
Posted by Ken Tucker on Friday, August 04, 2006 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed