Locations of visitors to this page


Onteora Software - DataGridView

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

DataGridViewCombobox AutoComplete

Here is a quick example on using an autocomplete combobox in the DataGridView.  In this example I load all the possible values for the combobox into a AutoCompleteStringCollection and make that the DataGridViewComboBox's datasource.  In the editingControl showing event you need to set the ComboBox's DropDownStyle, and the auto complete settings.

 

Imports System.Data.SqlClient

Public Class Form1
    Dim scAutoComplete As New AutoCompleteStringCollection

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strConn As String
        Dim da As SqlDataAdapter
        Dim conn As SqlConnection
        Dim ds As New DataSet
        strConn = "Server = .\SQLEXPRESS;Database = NorthWind; Integrated Security = SSPI;"
        conn = New SqlConnection(strConn)
        da = New SqlDataAdapter("Select * from [Orders]", conn)
        da.Fill(ds, "Orders")
        DataGridView1.DataSource = ds.Tables("Orders")

        Dim cmd As New SqlCommand("Select CustomerID From customers", conn)
        Dim dr As SqlDataReader
        conn.Open()
        dr = cmd.ExecuteReader
        Do While dr.Read
            scAutoComplete.Add(dr.GetString(0))
        Loop
        conn.Close()

        Dim dgvcbc As New DataGridViewComboBoxColumn
        With dgvcbc
            .DataPropertyName = "CustomerID"
            .DataSource = scAutoComplete
            .HeaderText = "Customer ID"
        End With
        DataGridView1.Columns.Remove("CustomerID")
        DataGridView1.Columns.Insert(1, dgvcbc)
    End Sub

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCell.ColumnIndex = 1 AndAlso TypeOf e.Control Is ComboBox Then
            With DirectCast(e.Control, ComboBox)
                .DropDownStyle = ComboBoxStyle.DropDown
                .AutoCompleteMode = AutoCompleteMode.SuggestAppend
                .AutoCompleteSource = AutoCompleteSource.CustomSource
                .AutoCompleteCustomSource = scAutoComplete
            End With
        End If
    End Sub

End Class

kick it on DotNetKicks.com

Currently rated 2.0 by 1 people

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

Categories: DataGridView | VB
Posted by Ken Tucker on Wednesday, March 26, 2008 6:01 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Datagridview and Linq issue

I had some one ask me an interesting question about using linq with the datagridview

When I bind a datagridview to this query

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select s
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

Why do I get these results?

image

The answer the datagridview will show the properties of the class in the list bound to the datagridview.  In this case we are bound to a list of string and the only bindable property is its Length.  

If you change the query to this

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select New With {.Name = s}
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

You will get the expected results

image  

I should also mention that you can not bind a datagridview to a linq query directory.  You need to bind the query to a bindingsource and bind the datagridview to the bindingsource or bind the datagridview to the queries ToList method.



kick it on DotNetKicks.com

Be the first to rate this post

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

Categories: DataGridView | Linq | VB
Posted by Ken Tucker on Monday, January 28, 2008 6:35 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Paging a Windows Forms DataGridView with LINQ

Since Visual Studio 2008 is due out by the end of the Month I am updating some of my datagridview samples for LINQ.

To start off create a new windows forms application in VS 2008 make sure you select FrameWork 3.5 so you can use linq

 

 

 

I now added a new Linq to Sql designer to the project and named it Northwind.  Drag the Northwind Products Table on to the design surface from the Server Explorer.

 

 

 

 

 

On your windows forms add a DataGridView (DataGridView1) and a NumericUpDown control (nuPage).  For this example I will have the datagridview show 15 items at a time.  In the form load event we will figure out how many pages there are and load the first 15 items into the datagridview.  In the NumericUpdown controls value changed event we will update the data displayed

 

Public Class Form1
    Dim bs As New BindingSource

    Private intPages As Integer
    Dim db As New NorthwindDataContext

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        intPages = Math.Ceiling(db.Products.Count / 15)
        nuPage.Maximum = intPages
        nuPage.Minimum = 1
        Dim p = From prod In db.Products _
                Select prod Skip 0 Take 15
        bs.DataSource = p
        bs.AllowNew = False
        DataGridView1.DataSource = bs
    End Sub


    Private Sub nuPage_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles nuPage.ValueChanged
        Dim p = From prod In db.Products _
                Select prod Skip (nuPage.Value - 1) * 15 Take 15
        bs.DataSource = p
    End Sub
End Class

Be the first to rate this post

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

Categories: DataGridView | Linq | VS 2008
Posted by Ken Tucker on Tuesday, November 06, 2007 2:43 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Using Linq for Master Detail in a DataGridView

Using Linq for Master Detail in a DataGridView


I saw in the MSDN forums someone asking how to do a master details relationship with Linq. It is actually pretty simple. Here are the steps involved on creating the relationship. I am using VS 2008 Beta 2 for this example.

  1. Open up Visual Studio 2008 Beta 2 and create a windows forms Application

  2. Add a new Linq 2 Sql classes to the project named Northwind.dbml

  3. Drag the Northwind database's Orders and Order Details table onto the surface

  4. Save the project and build it

  5. Open the data sources window and add a new object data source. Select the orders table

  6. Drag the orders table on your windows form

  7. Drag the orders_details table on the form

  8. In the form load event add this code



VB

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

Dim db As New NorthwindDataContext

OrderBindingSource.DataSource = From o In db.Orders Select o

End Sub

C#

private void Form1_Load(object sender, EventArgs e)

{

NorthwindDataContext db = new NorthwindDataContext();

orderBindingSource.DataSource = from o in db.Orders select o;

}


Be the first to rate this post

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

Categories: DataGridView | Linq
Posted by Ken Tucker on Saturday, August 18, 2007 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Sql Endpoint and DataGridView

Sql Endpoint and DataGridView

SQL Server 2005 allows you to create webservices for accessing the data in a database.  These webservices are call SQL End Points.  Lets start by creating a stored procedure to get the contact name and there titles for all the customers in the northwind database.  

Create PROCEDURE [dbo].[GetContacts]
AS
BEGIN
    SET NOCOUNT ON;

    SELECT [ContactName],[ContactTitle] FROM Customers ORDER BY [ContactName];
END

Now we can create the end point.  Note for this example I am using port 88 for the end point to prevent errors if you have IIS installed.

CREATE ENDPOINT NW_Contacts
    STATE = Started
AS HTTP
    (
        PATH = '/Contacts',
        AUTHENTICATION = (INTEGRATED),
        PORTS = (CLEAR),
CLEAR_PORT = 88,
        SITE = '*'
    )
FOR SOAP
    (
        WEBMETHOD 'GetContacts'
            (NAME = 'Northwind.dbo.GetContacts'),
        WSDL = DEFAULT,
        DATABASE = 'Northwind',
        NAMESPACE = DEFAULT
    )


Now we need to create a windows forms application.  I called the app EndPointTest.  On the form add a datagridview and set its dock property to fill.
Then add a web reference to the app.  For the url use http://localhost:88/contacts?WSDL.  For the name I used ContactEndPoint.
Here is some sample code for filling the datagridview with data from the end point

Imports System.Net

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim ws As New ContactEndPoint.NW_Contacts

        ws.Credentials = CredentialCache.DefaultCredentials

        Dim ds As DataSet = TryCast(ws.GetContacts(0), DataSet)
        DataGridView1.DataSource = ds.Tables(0)

    End Sub
End Class

Currently rated 2.7 by 3 people

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

Categories: DataGridView | Sql
Posted by Ken Tucker on Wednesday, June 27, 2007 1:12 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Get XML string into a DataGridView

Get XML string into a DataGridView



In the msdn forums I see people asking how do they get a string that contains xml to display in the DataGridView. They way to do this is to read the string into a StringReader and use the DataSet,Readxml method to convert the xml into a datatable. Note the xml must be well formed for this to work.



 Dim srXML As New IO.StringReader(strXML)
 Dim dsXML As New DataSet
 dsXML.ReadXml(srXML)

 DataGridView1.DataSource = dsXML.Tables(0)

Be the first to rate this post

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

Categories: DataGridView | VB
Posted by Ken Tucker on Sunday, March 11, 2007 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Draw an Icon in a DataGridViewButtonCell

Draw an Icon in a DataGridViewButtonCell



Here is a simple example on how to draw in a DataGridViewButtonCell. In this example an icon is displayed when button is pushed and the icon is made invisible when its pushed again. I am storing the if the button has been pressed in the cell's tag. I use the cellPainting event to draw the icon when needed.


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 CSButtonColumn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String strConn = "Server = .\\SqlExpress;Database = Pubs;Integrated Security = SSPI;";
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(strConn);
            SqlDataAdapter da = new SqlDataAdapter("Select * from titles", conn);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            DataGridViewButtonColumn bc = new DataGridViewButtonColumn();
            bc.Tag = false;
            dataGridView1.Columns.Insert(0, bc);
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                e.Value = "Repair";
                e.FormattingApplied = true;
            }
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0)
            {
                e.Paint(e.CellBounds, DataGridViewPaintParts.All);
                DataGridViewButtonCell bc = dataGridView1[0, e.RowIndex] as DataGridViewButtonCell;
                bool x;
                if (bc.Tag == null)
                {
                    x = false;
                }
                else
                {
                    x = (bool)bc.Tag;
                }
                if (x)
                {
                    Icon ico = new Icon("repair.ico");
                    e.Graphics.DrawIcon(ico, e.CellBounds.Left+3, e.CellBounds.Top+3 );
                }
                e.Handled = true;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0)
            {
                DataGridViewButtonCell bc = dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewButtonCell;
                if (bc.Tag == null)
                {
                    bc.Tag = true;
                }
                else
                {
                    bc.Tag = !(bool)bc.Tag;
                }
            }
        }
    }
}

 

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, February 07, 2007 11:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Data From Multiple Tables in a DataGridView

Data From Multiple Tables in a DataGridView



There is Msdn Knowledge base article which shows how to create a JoinView class. The JoinView class is for joining 2 tables together for data binding. Basically you load 2 or more tables into a dataset and set up some data relations for the related tables. When you create the Joinview the first argument is the main table, 2nd is a list of fields you want to show, 3rd is a filter, and 4th is the field to sort on. The last 2 arguments are option. Since the article includes a vb sample I am posting a c# example. I would recommend compiling JoinView.VB into a class so you use it with c#. I named my dll MSDNClasses.


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;
using MSDNClasses;

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

        DataSet ds = new DataSet();
        JoinView jv;

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(@"server=.\sqlexpress;integrated security=true;database=northwind");
            SqlDataAdapter daCust = new SqlDataAdapter(@"Select * From Customers", conn);
            SqlDataAdapter daEmp = new SqlDataAdapter(@"Select * From Employees", conn);
            SqlDataAdapter daOrd = new SqlDataAdapter(@"Select * From Orders", conn);

            daCust.Fill(ds, "Cust");
            daEmp.Fill(ds, "Emp");
            daOrd.Fill(ds, "Ord");

            // Create some data relations for the joinview to use

            ds.Relations.Add("CustOrd", ds.Tables["Cust"].Columns["CustomerID"], ds.Tables["Ord"].Columns["CustomerID"]);
            ds.Relations.Add("EmpOrd", ds.Tables["Emp"].Columns["EmployeeID"], ds.Tables["Ord"].Columns["EmployeeID"]);

            // Create Join View
            // Select fields for JoinView,  a filter to use, and Column to sort on

            jv = new JoinView(ds.Tables["Ord"],
                "OrderID,CustomerID,EmployeeID,OrderDate,CustOrd.CompanyName Company,CustOrd.ContactName Contact,CustOrd.ContactTitle Position,EmpOrd.FirstName,EmpOrd.LastName",
                "", "");

            dataGridView1.DataSource = jv;

        }
    }
}

Be the first to rate this post

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

Categories: DataGridView | C#
Posted by Ken Tucker on Saturday, December 30, 2006 11:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

AutoComplete in DataGridView

AutoComplete in DataGridView



In the datagridview's editing control showing event you have better access to the textboxes properties. Here is an example of adding autocomplete to the textbox.



VB Sample

Imports System.Data.SqlClient

Public Class Form1

    Dim scAutoComplete As New AutoCompleteStringCollection

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strConn As String
        Dim da As SqlDataAdapter
        Dim conn As SqlConnection
        Dim ds As New DataSet
        strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;"
        conn = New SqlConnection(strConn)
        da = New SqlDataAdapter("Select * from [Orders]", conn)
        da.Fill(ds, "Orders")
        DataGridView1.DataSource = ds.Tables("Orders")

        Dim cmd As New SqlCommand("Select CustomerID From customers", conn)
        Dim dr As SqlDataReader

        conn.Open()
        dr = cmd.ExecuteReader
        Do While dr.Read
            scAutoComplete.Add(dr.GetString(0))
        Loop
        conn.Close()
    End Sub

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCell.ColumnIndex = 1 AndAlso TypeOf e.Control Is TextBox Then
            With DirectCast(e.Control, TextBox)
                .AutoCompleteMode = AutoCompleteMode.SuggestAppend
                .AutoCompleteSource = AutoCompleteSource.CustomSource
                .AutoCompleteCustomSource = scAutoComplete
            End With
        End If
    End Sub
End Class

 

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.Data.SqlClient;


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

        AutoCompleteStringCollection scAutoComplete = new AutoCompleteStringCollection();

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            String strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;";
            SqlConnection conn = new SqlConnection(strConn);
            SqlDataAdapter da = new SqlDataAdapter("Select * from [Orders]", conn);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            SqlCommand cmd = new SqlCommand("Select CustomerID From customers", conn);
            SqlDataReader dr;
                conn.Open();
                dr=cmd.ExecuteReader();
                while(dr.Read())
                {
                    scAutoComplete.Add(dr.GetString(0));
                }
                conn.Close();
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView1.CurrentCellAddress.X == 1)
            {
                TextBox txt = e.Control as TextBox;
                txt.AutoCompleteCustomSource = scAutoComplete;
                txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
            }
        }
    }
}

Currently rated 5.0 by 1 people

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

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

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