Blue Theme Orange Theme Green Theme Red Theme
 
ASP.Net 4 Hosting is here
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » How to work with Data Grid View in VB.Net

How to work with Data Grid View in VB.Net


In this article we will see the most common use of the datagrid control. Lets set up out datagrid.

Total page views :  8892
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Introduction:

Microsoft.net framework ships with many usefull controls. These controls makes the life of developer easy by providing them with the functinality they want.

Among those many controls is the DataGrid control which helps the developer to display the data on the screen in the format of an arranged table. Datagrid is one of the 3 templated controls provided by the Microsoft.net framework. The other two are DataList and the Repeator control. Many new controls are being developed everyday but their basic idea is inherited from the classic DataGrid control.

In this article we will see the most common use of the datagrid control. Lets set up out datagrid.

Setting up the Datagrid:

Lets first set up our datagrid.

  1. Drag and Drop the datagrid control from your toolbox to the webform.
  2. The datagrid will appear as a simple table.
  3. You can make the datagrid pretty by selecting the Auto format features.

Okay your datagrid is set up, lets add some columns.

Adding the Bound Columns:

Adding the bound colums in the datagrid is pretty simple.

  1. Right click on the datagrid and select Property Builder.
  2. Click on the Columns tab and uncheck "Generate columns automatically".
  3. Add three bound columns, give the columns some name in the column name field. And finally add the edit,update,cancel buttons which can be found under the button option.

Note: Please also note that the button type should be link button or else it wont work.
datagrid_azam_img1.jpg

Storing the database connection:

In this demo I am storing the database connection in the Web.config file. The database name is DBSnippets, which has one table known as tblPerson. Here is the web.config file.

<configuration>
    <
appSettings>
      <
add Key="ConnectionString" value="server=localhost;database=DBSnippets">
</appSettings>
  </configuration>

Okay till now we have made the Datagrid and also saved the connection string in the web.config file. Now the time has come to code and handle the events.

Lets first make the BindData method which will retrieve the contents from the database and bind it on the screen. This will be one of the most important methods since it will be called whenever the page is loaded for the first time.

   private void Page_Load(object sender, System.EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }
    }

As you see the BindData method is called when the page is not posted back. Now lets see the BindData method in details.

    public void BindData()
    {
        SqlCommand myCommand = new SqlCommand("SP_SELECT_PERSONS", myConnection);
        myCommand.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
        DataSet ds = new DataSet();
        myAdapter.Fill(ds, "tblPerson");
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        myDataGrid.DataSource = ds;
        myDataGrid.DataBind();
        myConnection.Close();
    }

Explanation of the BindData method:

  1. First we make a SqlCommand object and named it myCommand. The SqlCommand object takes a stored procedure as an input and the SqlConnection.
  2. We feed the command object to the DataAdapter object named as myAdapter.
  3. A dataset is declared which is filled with the result of the Stored procedure.
  4. myDataGrid.DataBind() binds the datagrid to the page. Don't forget to bind the grid or else it won't be displayed.
  5. Later we opened the connection and execute the query.

Now Lets see the stored procedure.

Stored Procedure:

CREATE PROCEDURE SP_SELECT_PERSONS
AS
SELECT * FROM tblPerson  GO

As you can see that the above Stored Procedure is pretty simple. All we are doing is we are just selected all the columns from the table person.

Lets now make the Edit method which will display textboxes inside the datagrid so that a user can insert data. This sort of editing is also known as Inline editing.

Making datagrid editable is pretty simple. All you to do is to code few lines in the EditCommand event of the datagrid. You can view all the events supported by DataGrid by selecting properties and than selecting the Thunder/Flash yellow sign at the top of the properties window.

Lets call our Edit DataGrid event Edit_DataGrid.

   private void Edit_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        // We use CommandEventArgs e to get the row which is being clicked
        // This also changes the DataGrid labels into Textboxes so user can edit them
        myDataGrid.EditItemIndex = e.Item.ItemIndex;
        // Always bind the data so the datagrid can be displayed.
        BindData();
   }

 When the Edit link button is clicked your DataGrid will look something like this:

datagrid_azam_img2.jpg

As you see when you click the edit link the update and the cancel link button automatically appears.

Lets now see the code for the Cancel Event. Cancel event is used when you are in the edit mode and you change your mind about not to edit. So you click the cancel link button and the Datagrid returns back to its orginal condition.

   private void Cancel_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        // All we do in the cancel method is to assign '-1' to the datagrid editItemIndex
        // Once the edititemindex is set to '-1' the datagrid returns back to its original condition
        myDataGrid.EditItemIndex = -1;
        BindData();
    }

Okay now we come to a slightly difficult step. We will carefully look at the Update method and see how it works.

    private void Update_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
        cName = (System.Web.UI.WebControls.TextBox)e.Item.Cells[1].Controls[0];
        SqlCommand myCommand = new SqlCommand("SP_UpdatePerson", myConnection);
        myCommand.CommandType = CommandType.StoredProcedure;
        myCommand.Parameters.Add(new SqlParameter("@PersonName", SqlDbType.NVarChar, 50));
        myCommand.Parameters["@PersonName"].Value = cName.Text;
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        myConnection.Close();
        myDataGrid.EditItemIndex = -1;
        BindData();
    }

Lets now dig into this method and see whats going on.

The name of the method as you can see is Update_DataGrid, this event is fired when you click the update link button which appears after clicking the edit button.

We declare a variable of TextBox type and call it cName. The reason of declaring a TextBox is that the value that we want is inside the TextBox which is inside the DataGrid control.

Later we made the SqlCommand object which takes stored procedure "SP_UpdatePerson", which will be discussed afterwords.

After marking the command object with the stored procedure we passed the parameter which is PersonName.
Finally we execute the Query and set the editItemIndex property of the DataGrid '-1' which will bring the datagrid back to its original form i.e without any textboxes.

Don't forget to bind the datagrid.

Update Stored Procedure:
CREATE PROCEDURE SP_UpdatePerson
@PersonName nvarchar(50)
AS
UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName;

Selecting Item from the Datagrid:

Another cool feature of the Datagrid control is that you can select any row from the datagrid and it will be displayed as the highligted row in the grid.

The highlight row event is called SelectedIndexChanged event. The event is called when the select column is clicked. The select column can be added to the datagrid using the property builder, just like we added "edit/cancel/update" link buttons.

   // This event is fired when the Select is clicked
    private void Select_DataGrid(object sender, System.EventArgs e)
    {
        // prints the value of the first cell in the DataGrid
        Label2.Text += myDataGrid.SelectedItem.Cells[0].Text;
    }

datagrid_azam_img3.jpg

This method is pretty simple. When the datagrid select link button is pressed. We retrieve the item from the datagrid which is residing on the same row on which the link button is pressed. As we can see above in the code that we are retrieving the value from the first column of the datagrid.

I hope you all liked the article.


Login to add your contents and source code to this article
 About the author
 
M Ahmad Bhandara
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.