Click here to Skip to main content
6,596,602 members and growing! (18,010 online)
Email Password   helpLost your password?
Database » Database » ADO.NET     Intermediate

Working with DataGrid in VC++.NET

By Arul Nayagam C A

This article demonstrates the DataGrid , ADO.NET components, and storing data into the database and retrieving from the same.
C++/CLI, VC7, VC7.1, Windows, .NET, ADO.NET, VS.NET2003, Dev
Posted:15 Dec 2004
Views:67,922
Bookmarked:19 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
5 votes for this article.
Popularity: 2.24 Rating: 3.20 out of 5

1
1 vote, 20.0%
2
2 votes, 40.0%
3
2 votes, 40.0%
4

5

Introduction

This is my small contribution from what I learnt in my walk towards VC++ .NET. It's a really simple and very often used scenario: working with DataGrid. Here, I developed a small application which creates database and stores the data (image), and also retrieves data from the database and displays it in the DataGrid.

Code Explanation

Requirements

  • MS Visual Studio .NET 2003
  • Windows XP
  • SQL Server 2000

I used SQL Server for database operations. The application shows how the values (image) are stored in the database and the grid is updated when changes are made in the database. This is the snapshot of my application.

Sample screenshot

Controls used

  • Buttons: Create Database, Select Image, Save to Database
  • PictureBox: PictureBox1
  • DataGrid: Datagrid1

Create the database

When you click the button 'Create Database', the table called Picture would be created in the SQL Server NorthWind database. If it is already present, it would be deleted and created again.

String* strSQL = 
        S"IF EXISTS (SELECT * FROM northwind.dbo.sysobjects WHERE NAME " 
        "= 'Picture' AND TYPE = 'u')\r\nBEGIN\r\nDROP " 
        "TABLE northwind.dbo.picture\r\nEND\r\nCREATE TABLE " 
        "Picture (PictureID Int IDENTITY(1,1) NOT NULL,[FileName] " 
        "Varchar(255) NOT NULL,Picture Image NOT NULL," 
        "CONSTRAINT [PK_Picture] PRIMARY KEY CLUSTERED(PictureID))";
Try
{
    SqlConnection* conCreate = new SqlConnection(strconString);
    SqlCommand* sqlCmd = new SqlCommand(strSQL,conCreate);
    conCreate->Open();
    sqlCmd->ExecuteNonQuery();
    conCreate->Close();

      MessageBox::Show(S"Table is Created Successfully",S"Table   
        Creation",MessageBoxButtons::OK,MessageBoxIcon::Information);

}
catch(System::Exception* ee)
{
    MessageBox::Show(ee->Message,S"Error",MessageBoxButtons::OK,
                         MessageBoxIcon::Information);
}

Place the code to create the table and declare the appropriate variables in the program.

Select Image

The open file dialog is used to select the particular image. When the Select Image button is clicked, the open file dialog would be displayed to select the image (BMP/GIF/JPG).

   openFileDialog1->InitialDirectory = S"C:\\";
   openFileDialog1->Filter = S"All  
                       Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg";
   openFileDialog1->FilterIndex = 2;

   if(openFileDialog1->ShowDialog()== DialogResult::OK)
    {
    pictureBox1->Image = Image::FromFile(openFileDialog1->FileName);
    pictureBox1->SizeMode = PictureBoxSizeMode::CenterImage;
    pictureBox1->BorderStyle = BorderStyle::Fixed3D;
    lblImage_Path->Text = openFileDialog1->FileName;

    }

Place the code in the Select Image button Click event.

Save to Database

When the Save to Database button is clicked, the selected image would be stored into the Picture table by means of converting it into a stream of bytes. After storing into database, refresh the DataGrid.

//To Convert the Image to Bytes

MemoryStream* mst = new MemoryStream();
pictureBox1->Image->Save(mst,pictureBox1->Image->RawFormat);
Byte BinaryImg[] = mst->GetBuffer();
mst->Close();

Then, insert the image name to the database.

//Insert into Table

conNwnd = new SqlConnection(strconString);
String* strSQL = S"INSERT INTO Picture" 
                  " (Filename, Picture)VALUES (@Filename, @Picture)";

//To Fill the DataGrid


sqlcmd = new SqlCommand(strSQL,conNwnd);
sqlcmd->Parameters->Add(new SqlParameter(S"@Filename", 
        SqlDbType::NVarChar,50))->Value = strImgFile[0];
sqlcmd->Parameters->Add(new SqlParameter(S"@Picture", 
        SqlDbType::Image))->Value = BinaryImg;

conNwnd->Open();
sqlcmd->ExecuteNonQuery();
conNwnd->Close();
RefreshTable();
MessageBox::Show(String::Concat(strImgFile[0],S" saved to Database."), 
       S"Image Status",MessageBoxButtons::OK,MessageBoxIcon::Information);

Here, RefreshTable function is used to refresh the grid.

RefreshTable()
conNwnd = new SqlConnection(strconString);
SqlDataAdapter* sqlDA = new SqlDataAdapter(S"Select PictureID,Filename," 
                        "Picture FROM Picture",conNwnd);
TableData->Clear();
sqlDA->Fill(TableData,INPUT_TABLE);
dataGrid1->DataSource = TableData->Tables->Item[INPUT_TABLE];

On the form Load call, this RefreshTable function displays the values from the database.

Conclusion

Using this small application, a beginner can understand the DataGrid and about database connections, and how to store and retrieve values from the database using VC++ .NET. Your comments are always welcome which helps me to sharp my knowledge more.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Arul Nayagam C A


Member
Finished MCA and Working as a Software Engineer for HCL,Chennai.Knowledge on VB,C#.NET,ASP.NET and VC++.NET.
Occupation: Web Developer
Location: India India

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 14 of 14 (Total in Forum: 14) (Refresh)FirstPrevNext
Questionregarding datagrid Pinmemberebfru21:59 23 Apr '08  
GeneralSelected image should be editable Pinmemberminad_7863:46 21 Feb '07  
GeneralFinding the column names thatmake up an Index PinmemberAlexEvans22:43 12 Oct '06  
Generalhow to use ado.net in mfc? Pinmembersophiaia15:47 14 Apr '06  
QuestionNEED HELP PLZZ!! Pinmemberhbjs15:42 2 Feb '06  
QuestionDatagrid formatting?? Pinmembersalaikumar21:49 9 Oct '05  
GeneralCode? Pinmemberyoung18:32 20 Jan '05  
GeneralRe: Code? PinmemberArul Nayagam C A2:08 11 Feb '05  
GeneralRe: Code? PinmemberMember 475021311:23 7 Jan '08  
GeneralMemoryStream Pinmembercucubau21:24 26 Dec '04  
GeneralRe: MemoryStream PinmemberArul Nayagam C A22:50 26 Dec '04  
GeneralDatagrid article? Pinmemberjavanic4:29 23 Dec '04  
GeneralRe: Datagrid article? PinmemberArul Nayagam C A18:13 26 Dec '04  
GeneralSource code PinmemberAmul Baby19:52 23 Feb '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Dec 2004
Editor: Smitha Vijayan
Copyright 2004 by Arul Nayagam C A
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project