DataGridView in Windows Forms Tips, Tricks and Frequently Asked Questions(FAQ)



Similar documents
VB.NET - DATABASE ACCESS

Database Communica/on in Visual Studio/C# using Web Services. Hans- Pe=er Halvorsen, M.Sc.

Access Data Object (cont.)

ASP.NET Dynamic Data

5 Airport. Chapter 5: Airport 49. Right-click on Data Connections, then select Add Connection.

Relationships in WPF Applications

Creating Reports Using Crystal Reports

Conexión SQL Server C#

{ oledbdataadapter1.updatecommand.commandtext = "update personel set ad='" + textbox2.text + "' where id=" + textbox1.text; oledbconnection1.

In-Depth Guide Advanced Database Concepts

Visual Basic Programming. An Introduction

Introduction to Visual Basic and Visual C++ Database Foundation. Types of Databases. Data Access Application Models. Introduction to Database System

Working with Data in ASP.NET 2.0 :: Paging and Sorting Report Data Introduction. Step 1: Adding the Paging and Sorting Tutorial Web Pages

1. La classe Connexion class Connexion {

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio Lab version: Last updated: 12/10/2010.

MICROSOFT ACCESS 2003 TUTORIAL

Hands-On Lab. Client Workflow. Lab version: Last updated: 2/23/2011

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Visual Basic 2010 Essentials

Microsoft Excel 2013: Macro to apply Custom Margins, Titles, Gridlines, Autofit Width & Add Macro to Quick Access Toolbar & How to Delete a Macro.

How To Create A Database In Araba

SQL injection attacks SQL injection user input SQL injection SQL Command parameters Database account. SQL injection attacks Data Code

Hands-On Lab. Building Applications in Silverlight 4 Module 8: Advanced OOB and MEF. Event Administrator Dashboard

Bookstore Application: Client Tier

FINACS INVENTORY Page 1 of 9 INVENTORY TABLE OF CONTENTS. 1. Stock Movement Physical Stock Adjustment...7. (Compiled for FINACS v 2.12.

Deleting A Record Updating the Database Binding Data Tables to Controls Binding the Data Table to the Data Grid View...

Ambientes de Desenvolvimento Avançados

Microsoft Access 2007

SQL Server Database Web Applications

Form Tasarımı - 5. Veri Tabanı Veri tabanı ismi; m Tablo ismi; mt

ECDL / ICDL Spreadsheets Syllabus Version 5.0

REPORT DESIGN GUIDE. Version 6.5

1. Create SQL Database in Visual Studio

آموزش DataGrid در WPF به همراه صفحه بندي و جستجوي انتخابی. کلیک کن

Understanding Start-Up Costs

CREATING EXCEL PIVOT TABLES AND PIVOT CHARTS FOR LIBRARY QUESTIONNAIRE RESULTS

Introduction to the BackgroundWorker Component in WPF

2. Modify default.aspx and about.aspx. Add some information about the web site.

Downloading RIT Account Analysis Reports into Excel

Microsoft Access 2010 Overview of Basics

When a variable is assigned as a Process Initialization variable its value is provided at the beginning of the process.

Creating and Managing Online Surveys LEVEL 2

BACKING UP A DATABASE

IENG2004 Industrial Database and Systems Design. Microsoft Access I. What is Microsoft Access? Architecture of Microsoft Access

Changing the Display Frequency During Scanning Within an ImageControls 3 Application

Access Queries (Office 2003)

Using AND in a Query: Step 1: Open Query Design

Microsoft Excel Basics

Basic Excel Handbook

Create Charts in Excel

USER GUIDE Appointment Manager

CPM release notes

How to Customize Printing Layouts with the Print Layout Designer

Importing Data from a Dat or Text File into SPSS

BID2WIN Workshop. Advanced Report Writing

PROCEDURE INSERTION(NUM IN EMPLOYES.NUMEMP%TYPE, NOM VARCHAR2, PRENOM IN VARCHAR2, PPHOTO IN BLOB, SALAIRE IN NUMBER);

Real-World ASP.NET: Building a Content Management System

Introduction to Visual Basic and Visual C++ Introduction to Control. TextBox Control. Control Properties. Lesson 5

Visual Web Development

EXCEL 2007 VLOOKUP FOR BUDGET EXAMPLE

EViews Database Extension Interface

Supporting Data Set Joins in BIRT

How To: Create a Crystal Report from ADO.NET Dataset using Visual Basic.NET

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

Microsoft Using an Existing Database Amarillo College Revision Date: July 30, 2008

Page Create and Manage a Presentation 1.1 Create a Presentation Pages Where Covered

Microsoft Excel Tips & Tricks

Election 2012: Real- Time Monitoring of Election Results

Crystal Reports for Visual Studio.NET

- Suresh Khanal. Microsoft Excel Short Questions and Answers 1

Microsoft Excel Training - Course Topic Selections

Q&As: Microsoft Excel 2013: Chapter 2

Visual COBOL ASP.NET Shopping Cart Demonstration

SPREADSHEETS. TIP! Whenever you get some new data, save it under a new name! Then if you mess things up, you can always go back to the original.

Bronson Door Company Web Site

USER GUIDE. Unit 5: Tools & Modules. Chapter 3: Forms & Surveys

Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring

Aras Corporation Aras Corporation. All rights reserved. Notice of Rights. Notice of Liability

3 What s New in Excel 2007

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

How to Download Census Data from American Factfinder and Display it in ArcMap

Access II 2007 Workshop

Excel 2007: Basics Learning Guide

Spreadsheet - Introduction

Word 2003 Tables and Columns

STATGRAPHICS Online. Statistical Analysis and Data Visualization System. Revised 6/21/2012. Copyright 2012 by StatPoint Technologies, Inc.

ADOBE READER AND ACROBAT

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

CRM Setup Factory Installer V 3.0 Developers Guide

8 CREATING FORM WITH FORM WIZARD AND FORM DESIGNER

Microsoft Excel 2010 Tutorial

BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6)

Excel. Microsoft Office s spreadsheet application can be used to track. and analyze numerical data for display on screen or in printed

Axis Tutorial. Axis Tutorial

Company Setup 401k Tab

Transcription:

DataGridView in Windows Forms Tips, Tricks and Frequently Asked Questions(FAQ) DataGridView control is a Windows Forms control that gives you the ability to customize and edit tabular data. It gives you number of properties, methods and events to customize its appearance and behavior. In this article, we will discuss some frequently asked questions and their solutions. These questions have been collected from a variety of sources including some newsgroups, MSDN site and a few, answered by me at the MSDN forums. Tip 1 Populating a DataGridView /Wypełnienie DGV/ In this short snippet, we will populate a DataGridView using the LoadData() method. This method uses the SqlDataAdapter to populate a DataSet. The table Orders in the DataSet is then bound to the BindingSource component which gives us the flexibility to choose/modify the data location. public partial class Form1 : Form private SqlDataAdapter da; private SqlConnection conn; BindingSource bsource = new BindingSource(); DataSet ds = null; string sql; public Form1() InitializeComponent(); private void btnload_click(object sender, EventArgs e) LoadData(); private void LoadData() string connectionstring = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;"; conn = new SqlConnection(connectionString); sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders"; da = new SqlDataAdapter(sql, conn); conn.open(); ds = new DataSet(); SqlCommandBuilder commandbuilder = new SqlCommandBuilder(da); da.fill(ds, "Orders"); bsource.datasource = ds.tables["orders"]; dgv.datasource = bsource; Public Partial Class Form1 Inherits Form Private da As SqlDataAdapter Private conn As SqlConnection Private bsource As BindingSource = New BindingSource() Private ds As DataSet = Nothing Private sql As String Public Sub New() InitializeComponent() Private Sub btnload_click(byval sender As Object, ByVal e As EventArgs) LoadData() 1

Private Sub LoadData() Dim connectionstring As String = "Data Source=localhost;Initial Catalog=Northwind;" & "Integrated Security=SSPI;" conn = New SqlConnection(connectionString) sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," & "ShipName, ShipCountry FROM Orders" da = New SqlDataAdapter(sql, conn) conn.open() ds = New DataSet() Dim commandbuilder As SqlCommandBuilder = New SqlCommandBuilder(da) da.fill(ds, "Orders") bsource.datasource = ds.tables("orders") dgv.datasource = bsource End Class Tip 2 Update the data in the DataGridView and save changes in the database / Aktualizacji danych w DataGridView i zapisać zmiany w bazie danych/ After editing the data in the cells, if you would like to update the changes permanently in the database, use the following code: private void btnupdate_click(object sender, EventArgs e) DataTable dt = ds.tables["orders"]; this.dgv.bindingcontext[dt].endcurrentedit(); this.da.update(dt); Private Sub btnupdate_click(byval sender As Object, ByVal e As EventArgs) Dim dt As DataTable = ds.tables("orders") Me.dgv.BindingContext(dt).EndCurrentEdit() Me.da.Update(dt) Tip 3 Display a confirmation box before deleting a row in the DataGridView / Wyświetlić okno potwierdzenia przed usunięciem wiersza w DataGridView / Handle the UserDeletingRow event to display a confirmation box to the user. If the user confirms the deletion, delete the row. If the user clicks cancel, set e.cancel = true which cancels the row deletion. private void dgv_userdeletingrow(object sender, DataGridViewRowCancelEventArgs e) if (!e.row.isnewrow) DialogResult res = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (res == DialogResult.No) e.cancel = true; Private Sub dgv_userdeletingrow(byval sender As Object, ByVal e As DataGridViewRowCancelEventArgs) If (Not e.row.isnewrow) Then Dim res As DialogResult = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) If res = DialogResult.No Then e.cancel = True 2

Tip 4 How to autoresize column width in the DataGridView /Jak automatycznie dopasować szerokość kolumny w DataGridView / The snippet shown below, first auto-resizes the columns to fit its content. Then the AutoSizeColumnsMode is set to the DataGridViewAutoSizeColumnsMode.AllCells enumeration value which automatically adjust the widths of the columns when the data changes. private void btnresize_click(object sender, EventArgs e) dgv.autoresizecolumns(); dgv.autosizecolumnsmode = DataGridViewAutoSizeColumnsMode.AllCells; Private Sub btnresize_click(byval sender As Object, ByVal e As EventArgs) dgv.autoresizecolumns() dgv.autosizecolumnsmode = DataGridViewAutoSizeColumnsMode.AllCells Tip 5 - Select and Highlight an entire row in DataGridView /Wybierz i zaznacz cały wiersz w DataGridView/ int rowtobeselected = 3; // third row if (dgv.rows.count >= rowtobeselected) // Since index is zero based, you have to subtract 1 dgv.rows[rowtobeselected - 1].Selected = true; Dim rowtobeselected As Integer = 3 ' third row If dgv.rows.count >= rowtobeselected Then ' Since index is zero based, you have to subtract 1 dgv.rows(rowtobeselected - 1).Selected = True Tip 6 - How to scroll programmatically to a row in the DataGridView / Jak programowo przewinąć do zadanego wiersza w DataGridView / The DataGridView has a property called FirstDisplayedScrollingRowIndex that can be used in order to scroll to a row programmatically. int jumptorow = 20; if (dgv.rows.count >= jumptorow && jumptorow >= 1) dgv.firstdisplayedscrollingrowindex = jumptorow; dgv.rows[jumptorow].selected = true; Dim jumptorow As Integer = 20 If dgv.rows.count >= jumptorow AndAlso jumptorow >= 1 Then dgv.firstdisplayedscrollingrowindex = jumptorow dgv.rows(jumptorow).selected = True Tip 7 - Calculate a column total in the DataGridView and display in a textbox / Obliczyć łączną kolumny w DataGridView i wyświetlać w polu tekstowym / A common requirement is to calculate the total of a currency field and display it in a textbox. In the snippet below, we will be calculating the total of the Freight field. We will then display the data in a textbox by formatting the result (observe the ToString("c")) while displaying the data, which displays the culture-specific currency. 3

private void btntotal_click(object sender, EventArgs e) if(dgv.rows.count > 0) txttotal.text = Total().ToString("c"); private double Total() double tot = 0; int i = 0; for (i = 0; i < dgv.rows.count; i++) tot = tot + Convert.ToDouble(dgv.Rows[i].Cells["Freight"].Value); return tot; Private Sub btntotal_click(byval sender As Object, ByVal e As EventArgs) If dgv.rows.count > 0 Then txttotal.text = Total().ToString("c") Private Function Total() As Double Dim tot As Double = 0 Dim i As Integer = 0 For i = 0 To dgv.rows.count - 1 tot = tot + Convert.ToDouble(dgv.Rows(i).Cells("Freight").Value) Next i Return tot End Function Tip 8 - Change the Header Names in the DataGridView /Zmiana nazw nagłówków w DataGridView / If the columns being retrieved from the database do not have meaningful names, we always have the option of changing the header names as shown in this snippet: private void btnchange_click(object sender, EventArgs e) dgv.columns[0].headertext = "MyHeader1"; dgv.columns[1].headertext = "MyHeader2"; Private Sub btnchange_click(byval sender As Object, ByVal e As EventArgs) dgv.columns(0).headertext = "MyHeader1" dgv.columns(1).headertext = "MyHeader2" Tip 9 - Change the Color of Cells, Rows and Border in the DataGridView / Zmień kolor komórek, wierszy i Granicznej w DataGridView / private void btncellrow_click(object sender, EventArgs e) // Change ForeColor of each Cell this.dgv.defaultcellstyle.forecolor = Color.Coral; // Change back color of each row this.dgv.rowsdefaultcellstyle.backcolor = Color.AliceBlue; // Change GridLine Color this.dgv.gridcolor = Color.Blue; // Change Grid Border Style this.dgv.borderstyle = BorderStyle.Fixed3D; Private Sub btncellrow_click(byval sender As Object, ByVal e As EventArgs) ' Change ForeColor of each Cell Me.dgv.DefaultCellStyle.ForeColor = Color.Coral ' Change back color of each row Me.dgv.RowsDefaultCellStyle.BackColor = Color.AliceBlue 4

' Change GridLine Color Me.dgv.GridColor = Color.Blue ' Change Grid Border Style Me.dgv.BorderStyle = BorderStyle.Fixed3D Tip 10 - Hide a Column in the DataGridView /Ukrywanie kolumny w DataGridView/ If you would like to hide a column based on a certain condition, here s a snippet for that. private void btnhide_click(object sender, EventArgs e) this.dgv.columns["employeeid"].visible = false; Private Sub btnhide_click(byval sender As Object, ByVal e As EventArgs) Me.dgv.Columns("EmployeeID").Visible = False Tip 11 - Handle SelectedIndexChanged of a ComboBox in the DataGridView / Uchwyt SelectedIndexChanged z ComboBox w DataGridView / To handle the SelectedIndexChanged event of a DataGridViewComboBox, you need to use the DataGridView.EditingControlShowing event as shown below. You can then retrieve the selected index or the selected text of the combobox. private void datagridview1_editingcontrolshowing(object sender, DataGridViewEditingControlShowingEventArgs e) ComboBox editingcombobox = (ComboBox)e.Control; if(editingcombobox!= null) editingcombobox.selectedindexchanged += new System.EventHandler(this.editingComboBox_SelectedIndexChanged); private void editingcombobox_selectedindexchanged(object sender, System.EventArgs e) ComboBox combobox1 = (ComboBox)sender; // Display index MessageBox.Show(comboBox1.SelectedIndex.ToString()); // Display value MessageBox.Show(comboBox1.Text); Private Sub datagridview1_editingcontrolshowing(byval sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Dim editingcombobox As ComboBox = CType(e.Control, ComboBox) If Not editingcombobox Is Nothing Then AddHandler editingcombobox.selectedindexchanged, AddressOf editingcombobox_selectedindexchanged Private Sub editingcombobox_selectedindexchanged(byval sender As Object, ByVal e As System.EventArgs) Dim combobox1 As ComboBox = CType(sender, ComboBox) ' Display index MessageBox.Show(comboBox1.SelectedIndex.ToString()) ' Display value MessageBox.Show(comboBox1.Text) Tip 12 - Change Color of Alternate Rows in the DataGridView /Zmień kolor co drugiego wiersza w DataGridView / private void btnalternate_click(object sender, EventArgs e) this.dgv.rowsdefaultcellstyle.backcolor = Color.White; 5

this.dgv.alternatingrowsdefaultcellstyle.backcolor = Color.Aquamarine; Private Sub btnalternate_click(byval sender As Object, ByVal e As EventArgs) Me.dgv.RowsDefaultCellStyle.BackColor = Color.White Me.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine Tip 13 - Formatting Data in the DataGridView /Formatowanie danych w DataGridView / The DataGridView exposes properties that enable you to format data such as displaying a currency column in the culture specific currency or displaying nulls in a desired format and so on. private void btnformat_click(object sender, EventArgs e) // display currency in culture-specific currency for this.dgv.columns["freight"].defaultcellstyle.format = "c"; // display nulls as 'NA' this.dgv.defaultcellstyle.nullvalue = "NA"; Private Sub btnformat_click(byval sender As Object, ByVal e As EventArgs) ' display currency in culture-specific currency for Me.dgv.Columns("Freight").DefaultCellStyle.Format = "c" ' display nulls as 'NA' Me.dgv.DefaultCellStyle.NullValue = "NA" Tip 14 Change the order of columns in the DataGridView /Zmienić kolejność kolumn w DataGridView / In order to change the order of columns, just set the DisplayIndex property of the DataGridView to the desired value. Remember that the index is zero based. private void btnreorder_click(object sender, EventArgs e) dgv.columns["customerid"].displayindex = 5; dgv.columns["orderid"].displayindex = 3; dgv.columns["employeeid"].displayindex = 1; dgv.columns["orderdate"].displayindex = 2; dgv.columns["freight"].displayindex = 6; dgv.columns["shipcountry"].displayindex = 0; dgv.columns["shipname"].displayindex = 4; Private Sub btnreorder_click(byval sender As Object, ByVal e As EventArgs) dgv.columns("customerid").displayindex = 5 dgv.columns("orderid").displayindex = 3 dgv.columns("employeeid").displayindex = 1 dgv.columns("orderdate").displayindex = 2 dgv.columns("freight").displayindex = 6 dgv.columns("shipcountry").displayindex = 0 dgv.columns("shipname").displayindex = 4 I hope this article was useful and I thank you for viewing it. 6