Menu Horisontal

Sabtu, 28 April 2012

Highlighting Record in Winform DataGridView



Kontrol Winform DataGridView mempunyai sebuah event yang dapat kita gunakan salah satunya untuk memberikan warna tertentu properti back color dan fore color dengan kriteria record yang kita inginkan. Misalkan kita ingin memberi warna yang berbeda untuk record dimana data produk yang dimiliki memiliki nilai stok sama dengan 0 (nol). Event yang dapat digunakan yaitu CellFormatting. Dengan memanfaatkan event tersebut kita dapat merubah style cell yang berbeda dengan nilai defaultnya, bahkan kita juga bisa menambahkan atau merubah teks ke cell tertentu.
Pada artikel kali ini saya akan membuat contoh aplikasi sederhana yang akan mengecek UnitsInStock table Products di database Northwind. Jika nilai stok nya 0 (nol) maka cell atau row tersebut akan diberi warna merah dengan teks nya berwarna kuning.
Dengan menggunakan DataGridViewCellFormattingEventArgs yang kita dapat menentukan kolom tertentu yang akan diberi warna back color atau teks color yang berbeda. Selain itu dari parameter tersebut dapat kita dapatkan value dari cell yang sedang aktif. Sehingga dari sini lah kita terapkan kriteria formatting cell yang diinginkan.

GUI Design: Transparent Form


Sumber : http://inf.uajy.ac.id/~sigit/2006/04/20/gui-design-transparent-form/

April 20th, 2006 Posted in .NETdesain komunikasi visual | 39 Comments »
Seringkali (bahkan setiap kali) pada saat kita membangun sebuah aplikasi atau menggunakannya, kita akan menemukan bahwa bentuk form yang kita buat atau lihat adalah standar yaitu segi empat (dengan nuansa Windows tentunya…). Bosankah Anda dengan bentuk form standar tersebut? Jika iya, sudah saatnya Anda mencoba untuk membuat form Anda menjadi tidak standar lagi bentuknya, alias lebih fancyl. Namun, jika Anda masih belum bosan, silahkan membuat form Anda tetap standar dan berikan sentuhan melalui pemilihan font, warna maupun penentuan layout yang proporsional dan menarik sehingga form Anda tetap bisa menjadi fancy.
Bagi Anda yang sudah bosan, saya akan mencoba memberikan sedikit tutorial tentang bagaimana membuat bentuk form kita menjadi tidak standar dan tentunya menjadi lebih menarik. Tools yang akan saya pakai ada 2, yaitu Adobe PhotoShop (Anda bisa pakai graphic design tools yang lain) untuk membuat image yang akan kita jadikan sebagai perwujudan dari bentuk form kita dan Microsoft Visual Studio .NET 2003 sebagai software development tools-nya.

Jumat, 27 April 2012

How to: Save Dataset Changes to a Database


.NET Framework 2.0

Sumber : http://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.80).aspx
After the data in your dataset has been modified and validated, you probably want to send the updated data back to a database. In order to send the modified data to a database, you call the Update method of a TableAdapter or data adapter. The adapter's Update method updates a single data table and executes the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.
NoteNote
Because attempting to update a data source with the contents of a dataset can result in errors, you should place the code that calls the adapter's Update method inside of a try/catch block.
The exact procedure to update a data source can vary depending on your business needs, but your application should include the following steps:
  1. Execute code that attempts sending updates to the database within a try/catch block.
  2. If an exception is caught, locate the data row that caused the error. For more information, see How to: Locate Rows that Have Errors.
  3. Reconcile the problem in the data row (programmatically if possible, or by presenting the invalid row to the user for modification), and then reattempt the update (HasErrors property, GetErrors method).

How to: Save Dataset Changes to a Database


Visual Studio 2010

Sumber : http://msdn.microsoft.com/en-us/library/xzb1zw3x.aspx
After the data in your dataset has been modified and validated, you probably want to send the updated data back to a database. In order to send the modified data to a database, you call the Update method of a TableAdapter or data adapter. The adapter's Update method updates a single data table and executes the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.
When saving data in related tables, Visual Studio provides a TableAdapterManager component that assists in performing saves in the proper order based on the foreign-key constraints defined in the database. For more information, see Hierarchical Update Overview.
NoteNote
Because attempting to update a data source with the contents of a dataset can result in errors, you should place the code that calls the adapter's Update method inside of a try/catch block.
The exact procedure to update a data source can vary depending on your business needs, but your application should include the following steps:

How to compare two tables for differences?


Execute the following Microsoft SQL Server 2008 T-SQL scripts in Query Editor to demonstrate the comparison of two tables for differences in rows and/or columns (cells).
------------
-- SQL SERVER COMPARE 2 TABLES FOR ROW & COLUMN DIFFERENCES
------------
-- TEMPLATE - SQL Server T-SQL compare two tables
SELECT Label='Found IN Table1, NOT IN Table2',* FROM 
(SELECT * FROM Table1
EXCEPT
SELECT * FROM Table2) x
UNION ALL
SELECT Label='Found IN Table2, NOT IN Table1',* FROM
(SELECT * FROM Table2
EXCEPT
SELECT * FROM Table1) y
GO
------------

Math Functions


Table 6-8. Math Functions
Function Name
Description
Abs(number)
Return the absolute value.
Fix(number, decimals)
Return a number with a specified number of significant digits.
Int(number),� numerator \ denominator
Return the integer portion of a fractional number.
Pi
3.14...
Remainder(numerator, denominator),
Return the remainder of dividing the numerator by the denominator.
numerator Mod denominator
Return the remainder of dividing the numerator by the denominator.
Round(number, decimals)
Round up a number with a specified number of significant digits.
Sgn(number)
Return a number's sign.
Sqr(number), Exp(number), Log(number)
The standard arithmetic functions.
Cos(number), Sin(number),Tan(number), Atn(number)
The standard scientific functions.
Most of these functions perform basic mathematical functionality. There are only a couple of interesting points to notice. Working with whole numbers and decimals is done numerous ways. The Fix() and Round() functions take a fractional number and truncate it to a specified number of digits. The Round() function will round up to the nearest decimal. The number of decimals to display is optional and the default is zero. The Int() function is similar to the Round() function except that it only returns the whole number and will round down to the nearest whole number. Table 6-9 shows how the three functions will return a different number depending upon the decimal portion and whether the number is positive or negative.


Table 6-9. Examples of Truncating Decimals
Function
1.9
-1.9
Fix()
1
-1
Round()
2
-2
Int()
1
-2
If you want to get the whole number and you have the numerator and denominator available. You can use the \ operator to perform integer division. This does the division and only returns the integer portion of the result. The Mod operator and Remainder() function return the remainder after doing the division.
'Demonstrate the integer division and the Mod operator
Formula = 10 \ 3'Returns 3
Formula = 10 mod 3'Returns 1
Formula = Remainder(10, 3)'Returns 1

Converting Data Types


Basic syntax is a type safe language that requires all constants and variables in the same formula to be of the same data type. It also requires you to pass constants and variables as arguments using the exact data type that the formula expects. Even though the data types in Basic syntax are fairly simple, you still have to make sure that they are compatible. Fortunately, this shouldn't cause problems because there are functions to convert between the different data types. Table 6-5 lists these conversion functions.

DateTime.ToString() Patterns



All the patterns:

0MM/dd/yyyy08/22/2006
1dddd, dd MMMM yyyyTuesday, 22 August 2006
2dddd, dd MMMM yyyyHH:mm Tuesday, 22 August 2006 06:30
3dddd, dd MMMM yyyyhh:mm tt Tuesday, 22 August 2006 06:30 AM
4dddd, dd MMMM yyyyH:mm Tuesday, 22 August 2006 6:30
5dddd, dd MMMM yyyyh:mm tt Tuesday, 22 August 2006 6:30 AM
6dddd, dd MMMM yyyy HH:mm:ssTuesday, 22 August 2006 06:30:07
7MM/dd/yyyy HH:mm08/22/2006 06:30
8MM/dd/yyyy hh:mm tt08/22/2006 06:30 AM
9MM/dd/yyyy H:mm08/22/2006 6:30
10MM/dd/yyyy h:mm tt08/22/2006 6:30 AM
10MM/dd/yyyy h:mm tt08/22/2006 6:30 AM
10MM/dd/yyyy h:mm tt08/22/2006 6:30 AM
11MM/dd/yyyy HH:mm:ss08/22/2006 06:30:07
12MMMM ddAugust 22
13MMMM ddAugust 22
14yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK2006-08-22T06:30:07.7199222-04:00
15yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK2006-08-22T06:30:07.7199222-04:00
16ddd, dd MMM yyyy HH':'mm':'ss 'GMT'Tue, 22 Aug 2006 06:30:07 GMT
17ddd, dd MMM yyyy HH':'mm':'ss 'GMT'Tue, 22 Aug 2006 06:30:07 GMT
18yyyy'-'MM'-'dd'T'HH':'mm':'ss2006-08-22T06:30:07
19HH:mm06:30
20hh:mm tt06:30 AM
21H:mm6:30
22h:mm tt6:30 AM
23HH:mm:ss06:30:07
24yyyy'-'MM'-'dd HH':'mm':'ss'Z'2006-08-22 06:30:07Z
25dddd, dd MMMM yyyy HH:mm:ssTuesday, 22 August 2006 06:30:07
26yyyy MMMM2006 August
27yyyy MMMM2006 August

The patterns for DateTime.ToString ( 'd' ) :

0MM/dd/yyyy08/22/2006

How to hide Gridview column programmatically?


Solution : From  http://asmaqureshi.blogspot.com/2011/09/how-to-hide-gridview-column.html

The Columns collection only stores the explicitly declared columns, so if you’re using autogenerated columns, the count will be zero.
If you’re using autogenerated column, after databind you could loop through the rows collection and make the appropriate cells invisible, like:

 GridView1.DataBind();
 if (GridView1.Columns.Count > 0)
 GridView1.Columns[0].Visible = false;
   else
  {
     GridView1.HeaderRow.Cells[0].Visible = false;
     foreach (GridViewRow gvr in GridView1.Rows)
  {
   gvr.Cells[0].Visible = false;
  }
 }

Use stored procedure to insert data VB.NET ( Windows forms )


SAVE DATA ON SQL SERVER THROUGH CALLING SP ( VB.NET FORMS ) 


Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim sqlSP As String = "stp_InsertUser"
Dim strConnection As String = "Data Source=.;Initial Catalog=DATAbaseName;User ID=sa;Password='111';"
Dim conn As New SqlConnection(strConnection)
conn.Open()
Dim cmd As New SqlCommand(sqlSP, conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("@UserLogin", SqlDbType.VarChar, 100, ParameterDirection.Input, _
False, 0, 0, "", DataRowVersion.Proposed, UsernameTextBox.Text))
cmd.Parameters.Add(New SqlParameter("@UserPwd", SqlDbType.VarChar, 100, ParameterDirection.Input, _
False, 0, 0, "", DataRowVersion.Proposed, PasswordTextBox.Text))
Try
cmd.ExecuteNonQuery()
MsgBox("User Added successfully ", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Please Enter UserName.", MsgBoxStyle.Critical)
End Try
cmd.Connection.Close()
End Sub

Selasa, 24 April 2012

Membuat Fungsi SelectedIndexChanged pada ComboBox di DataGridView


Dari :http://junindar.blogspot.com/2009/03/membuat-fungsi-selectedindexchanged.html



Pada artikel sebelumnya, telah di jelaskan bagaimana menambah control ComboBox pada DataGridView. Sekarang bagaimanakah membuat method SelectedIndexChange pada ComboBox tersebut.
Untuk control ComboBox yang diambil dari ToolBox method SelectedIndexChange sudah tersedia, Biasa nya fungsi ini di gunakan untuk menampilkan data/informasi jika nilai dari control ini dipilih.
Sedangkan untuk ComboBox pada DataGridView kita harus melakukan beberapa langkah dengan coding.

Bring to front MdiChild in Mdi Container - VB.Net


Dari : http://tentangvb.blogspot.com/search?updated-min=2012-01-01T00:00:00-08:00&updated-max=2013-01-01T00:00:00-08:00&max-results=3

Salah satu hal yang biasanya ada didalam aplikasi yang memaikai mode Kontiner MDI adalah fasilitas untuk mengecek apakah Mdichild telah aktiv di MDI kontiner, untuk kemudian di bawa ke posisi paling depan, ketimbang kita harus meng-createnya lagi. berikut ini adalah kode untuk keperluan tersebut(Ref: didapat dari milist bytes.com, dengan adopsi cara saya :) ), semoga bermanfaat.


Private Function isFormActive(ByVal TheFormName As String) As Boolean
        Try
            Dim ResultSearch As Boolean
            For Each myChild As Form In Me.MdiChildren
                If myChild.Name = TheFormName Then
                    ResultSearch = True
                    myChild.BringToFront()
                    Exit For
                Else
                    ResultSearch = False
                End If
            Next
            Return ResultSearch
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString, "Error to find the form", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

Mendeteksi Regional Dan Language system di VB.Net

Dari :  http://tentangvb.blogspot.com/search?updated-min=2010-01-01T00:00:00-08:00&updated-max=2011-01-01T00:00:00-08:00&max-results=4 

Untuk mendeteksi Regional dan Language yang dipakai pada suatu mesin kita dapat memanfaatkan Class Culture, yang bisa kita akses melalui cara berikut ini,

dim CurrentCulture as my.application.culture.name

Mengetahui system Regional dan Language yang dipakai pada suatu mesin akan memudahkan kita dalam menentukan format tanggal dan Angka, sehingga Aplikasi yang kita buat diharapkan dapat lebih flexible, tanpa harus kita setting secara manual setiap kali aplikasi di Install pada mesin tertentu. berikut contoh lengkapnya bagaimana cara mendeteksi Regional dan Language yang aktiv pada suatu mesin. kode berikut ini diambil dari ( http://msdn.microsoft.com/en-us/library/486cdc73(v=VS.80).aspx ) dengan sedikit tambahan.


Private Sub TestChangeCulture()
        ' Store the current culture.
        Dim currentculture As String = My.Application.Culture.Name
        MsgBox("Current culture is " & currentculture)
        Dim Des30 As New Date(2005, 12, 30, 15, 15, 15)
        Dim myNumber As Double = 2000.5
        MsgBox("Date represented in id-ID culture: " & Des30)
        MsgBox("Number Format 2000.5 dalam format Indonesia jadi :" & FormatNumber(myNumber, 2, TriState.True, TriState.True))
        My.Application.ChangeCulture("en-US")
        MsgBox("Date represented in en-US culture: " & Des30)
        MsgBox("Number Format 2000.5 dalam format en_US jadi :" & FormatNumber(myNumber, 2, TriState.True, TriState.True))
        ' 1/1/2005 3:15:15 PM
        My.Application.ChangeCulture("")
        MsgBox("Date represented in invariant culture" & jan1)
        ' 01/01/2005 15:15:15
        ' Restore the culture.
        My.Application.ChangeCulture(currentculture)
    End Sub

Transaksi di VB.Net Lanjutan


PRA KATA...
Pada saat membuat program terutama untuk aplikasi database, seringkali kita dihadapkan pada model penyimpanan master/detail atau header/detail. contoh nya pada kasus Order pembelian, penerimaan barang dan masih banyak lagi. tekhnik penyimpanannya sebenarnya bisa dilakukan dengan menyimpan headernya terlebih dahulu, baru kemudian kita tambahkan detailnya satu per satu, akan tetapi ada kalanya kita dihadapkan pada situasi bahwa data yang di masukan harus sukses tersimpan semuanya.. jika ada kesalahan.. entah yg disebabkan terputusnya koneksi secara tiba2 atau hal lainnya, maka data tersebut tidak boleh tersimpan hanya sebagian saja. Nah untuk situasi semacam ini memanfaatkan fungsi transaction pada SQLconnection menjadi perlu. untuk tujuan tersebutlah tulisan ini dibuat... ini hasil explorasi ku aja.. kalo ada yang lebih baik lagi tekhniknya boleh dong di sharing.. :)

STARTING..
Pada kasus ini saya menggunakan database SQLServer dg nama database test dan dua buah tabelTrsH sebagai tabel headernya dg field sbb (NoTrs Varchar(64), Desk Varchar(80) ) dan tabel TrsDsebagai tabel detailnya dg Field sbb (ID Smallint, NoTrs Varchar(64), Qty Smallint). Oleh karenanya jika ingin mencoba maka harus membuat database dan tabel-tabel tersebut.

Implementing SQL Server transactions with ADO.NET


ADO.NET provides everything you need to work with back-end data, which can be as simple as reading a set of data from one table to performing a transaction. A transaction allows you to group database operations to ensure that all the operations are performed because, if one operation fails, the whole transaction fails. Let's take a closer look at using transactions within the .NET Framework.
Transaction overview
A transaction is a group of operations combined into a logical unit of work. Developers use transactions to control and maintain the consistency and integrity of each action in a transaction, despite errors that might occur in the system.
This is an all-or-nothing approach: either all operations in the transaction are performed, or none. This approach is necessary in real-time applications.

Transaksi di VB.net


A transaction makes the database perform a series of actions as a unit. The classic example is moving money from one bank account to another. These two tasks must either both occur or neither occur. If the program removes the money from the first account and then crashes, the system loses money. If you perform the operations in the other order so the program adds money to the second account before crashing, the system "invents" money. Either way the database is no longer consistent.Operations in a transaction are guaranteed to either all occur or all not occur. Your program can also "rollback" a transaction to cancel it.
In VB .NET, you start a transaction by calling a connection object's BeginTransaction method. Then you create command objects to perform the tasks, passing their constructors the transaction object. You execute the commands and call the transaction object's Commit method to make the actions permanent or you call its Rollback method to cancel the transaction's actions.
The following code makes a transaction containing two record updates that modify some records' FirstName fields. It executes the commands and calls the transaction's Commit method.
' Make a transaction containing two actions and commit it.
Private Sub btnTransactionCommit_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnTransactionCommit.Click
    ' Open the connection.
    connUsers.Open()

    ' Make the transaction.
    Dim trans As OleDb.OleDbTransaction = _
        connUsers.BeginTransaction(IsolationLevel.ReadCommitted)

    ' Make a Command for this connection
    ' and this transaction.
    Dim cmd As New OleDb.OleDbCommand( _
        "UPDATE People SET FirstName=? WHERE LastName=?", _
        connUsers, _
        trans)

    ' Create parameters for the first command.
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", _
        txtFirstName1.Text))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        txtLastName1.Text))

    ' Execute the second command.
    cmd.ExecuteNonQuery()

    ' Create parameters for the second command.
    cmd.Parameters.Clear()
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", _
        txtFirstName2.Text))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        txtLastName2.Text))

    ' Execute the second command.
    cmd.ExecuteNonQuery()

    ' Commit the transaction.
    trans.Commit()

    ' Close the connection.
    connUsers.Close()

    ' Update the DataGrid.
    dsUsers.Clear()             ' Remove the old data.
    daUsers.Fill(dsUsers)       ' Reload the data.
    DataGrid1.ResetBindings()   ' Redisplay the data.
    MsgBox("OK")
End Sub
The following code performs the same actions except it calls the transaction's Rollback method to cancel the actions.
' Make a transaction containing two actions and roll it
' back.
Private Sub btnTransactionRollback_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnTransactionRollback.Click
    ' Open the connection.
    connUsers.Open()

    ' Make the transaction.
    Dim trans As OleDb.OleDbTransaction = _
        connUsers.BeginTransaction(IsolationLevel.ReadCommitted)

    ' Make a Command for this connection
    ' and this transaction.
    Dim cmd As New OleDb.OleDbCommand( _
        "UPDATE People SET FirstName='?' WHERE " & _
            "LastName='?'", _
        connUsers, _
        trans)

    ' Create parameters for the first command.
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", _
        txtFirstName1.Text))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        txtLastName1.Text))

    ' Execute the second command.
    cmd.ExecuteNonQuery()

    ' Create parameters for the second command.
    cmd.Parameters.Clear()
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", _
        txtFirstName2.Text))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        txtLastName2.Text))

    ' Execute the second command.
    cmd.ExecuteNonQuery()

    ' Roll the transaction back.
    trans.Rollback()

    ' Close the connection.
    connUsers.Close()

    ' Update the DataGrid.
    dsUsers.Clear()             ' Remove the old data.
    daUsers.Fill(dsUsers)       ' Reload the data.
    DataGrid1.ResetBindings()   ' Redisplay the data.
    MsgBox("OK")
End Sub

Copy datatable records to database

Hi,

I'm not very clear with the problem you have. But based onthe input let me try to explain.One option is to save the changes as soon as the user enters it, This is possible if we listen for ColumnChanged events coming off the DataTable and you can prompt a message whether to save the record or not when they try tp enter another one. you can also keep a hidden field in the DataTable to set status of the save.

For this to work you need to include the below import statement at the very begining

Imports System.Data.SqlClient

'Use the 127.0.0.1 if you are accessing local sql server, else give the IP of the SQL server
'Also give the username and passord

dim ConnectionString as String = "data source=127.0.0.1;user id=sa;password="

Senin, 23 April 2012

101 Ways to Manipulate the DataGridView Control (Bag 4)


Restricting Inputs
The previous section shows how you can validate the value for a cell after the user has finished typing it. However, in some situations this is not sufficient. A better way would be to prevent illegal characters from being entered in the first place. Using the same example from the previous section, you should prevent users from entering non-numeric characters in the Price field. For normal TextBox controls, this problem could be solved by servicing the KeyPress event. However, applying this technique to the DataGridView control requires some additional work.

First, service the EditingControlShowing event. This event is fired when the user tries to edit the content of a cell:

Private Sub DataGridView1_EditingControlShowing( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms. _
DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
'---restrict inputs on the fourth field---
If Me.DataGridView1.CurrentCell.ColumnIndex = 3 And _
Not e.Control Is Nothing Then
Dim tb As TextBox = CType(e.Control, TextBox)
'---add an event handler to the TextBox control---
AddHandler tb.KeyPress, AddressOf TextBox_KeyPress
End If
End Sub
Here, you will add a KeyPress event handler to the TextBox control that you want to restrict. This KeyPress event handler will be invoked when the user types into the cell and it is defined as follows:

101 Ways to Manipulate the DataGridView Control (Bag 3)


Displaying a ComboBox in Cell
Frequently, besides displaying text in a cell you may want to display a drop-down list box to allow users to select from a list of pre-determined values. In this case, you need to add a ComboBox to the cells in the desired column. The following code snippet adds a ComboBox control to the fifth column of the DataGridView control:

'---add columns to the DataGridView control---
DataGridView1.Columns.Add("ID", "Product ID")
DataGridView1.Columns.Add("Name", "Product Name")
DataGridView1.Columns.Add("Description", "Description")
DataGridView1.Columns.Add("Price", "Price")
'---create a new bindingsource control---
Dim bindingsource As New BindingSource
'---add the items into the control---
bindingsource.Add("Type A")
bindingsource.Add("Type B")
bindingsource.Add("Type C")
'---create a combobox column---
Dim comboBoxCol As New DataGridViewComboBoxColumn
'---set the header---
comboBoxCol.HeaderText = "Types"
'---data bind it---
comboBoxCol.DataSource = bindingsource
'---add a combobox column to the DataGridView control---
DataGridView1.Columns.Add(comboBoxCol)

101 Ways to Manipulate the DataGridView Control (Bagian 2)


Binding Using Typed Dataset
One very common use of the DataGridView control is binding to a table in a database. To illustrate this, I'll add a Typed DataSet to the current project. In Visual Studio 2005, right-click on the project name in Solution Explorer and select Add | New Item…. Select the DataSet template (use the default name of DataSet1.xsd) and click Add.

Launch Server Explorer (View | Server Explorer) and navigate to the Northwind sample database (assuming you have it installed on SQL Server/SQL Server Express). Drag and drop the Customers table onto the design surface of DataSet1.xsd. Figure 5 shows the creation of the typed dataset.
You have a choice of what to do for your next step. You can either bind the DataGridView control directly to the table adapter of the Customers table, like this:

'---create an instance of the table adapter---
Dim adapter As New CustomersTableAdapter
'---data bind to the DataGridView control---
DataGridView1.DataSource = adapter.GetData
Alternatively, you can use a BindingSource control:

101 Ways to Manipulate the DataGridView Control (Bagian1)


ne of the common controls that you will usually use in Windows Forms programming is the DataGridView control. The DataGridView control is a new control in Windows Forms 2.0 and it replaces the DataGrid control in Windows Forms 1.0. It is a very powerful and versatile control that is suitable for displaying tabular data from various data sources. The DataGridView control is so flexible—exposing so many properties, methods, and events—that it can be quite intimidating for beginners.



The aim of this article is to get you jumpstarted with DataGridView control so that you can be productive right away. I have tried to cover most of the common tasks, but this is by no means exhaustive coverage of the capabilities of the DataGridView control.In this article, I assume that you have a Windows application project and have a DataGridView control contained within the default Form1, as shown in Figure 1.
Binding to an Array
You can bind an array to a DataGridView control. Consider the following code snippet:

Dim arr() As String = _
{"Product 1", "Product 24", "Product 356"}
DataGridView1.DataSource = arr
Here, arr() is a string array and contains three elements. It is bound to the DataGridView control using the DataSource property. Figure 2 shows the result of the data binding.

Figure 1. To get started, create a new Windows application project and put a DataGridView control on Form1.

Figure 2. The result of binding a string array to a DataGridView control is shown.