Professional Documents
Culture Documents
MENU
How To Connect To Access Database And Display Data And Images In Datagridview In C Sharp Windows
Application
January 7,
by admin 2020
How To Connect To Access Database And Display Data And Images In Datagridview In C# Windows Application
Table of contents :
This Tutorial Shows How To Connect To Access Database And Display Data And Images In Datagridview In C Sharp Windows Application. This C# application inserts data entered by user to ms
access database. Also the images loaded from pc and displayed on picturebox are inserted in to the database as byte array. Then images are first converted to byte arrays before being stored in
access database. The first database column is of type integer which increments automatically whenever you insert a new row.
Go to start menu and search “Microsoft Access”. Then select it from the list.
HOW TO CREATE MICROSOFT ACCESS DATABASE AND TABLE
A New Database and table named “Database2” and “Table1” Gets created.
HOW TO CREATE MICROSOFT ACCESS DATABASE – NEW DATABASE AND TABLE CREATED
Add Field names like ( FullName,EmailAddress,PhoneNumberP,LanguageP, CountryP,GenderP,ImagePath, ImageFile etc.) and Datatypes.
HOW TO CREATE MICROSOFT ACCESS DATABASE – ADD FIELD NAMES AND DATATYPES
The newly created database is saved in documents folder unless you specified a different directory when creating the database.
VIDEO TUTORIAL
VIDEO TUTORIAL
In data source section “Microsoft Access Database File (OLE DB)” is selected by default.
How To Add Ms Access Database To Visual Studio 2010 – Microsoft Access Database File OLE DB Data Source
Choose Browse next to Database file name, and then navigate to your .accdb file and choose Open.
How To Add Ms Access Database To Visual Studio 2010 – Choose Browse next to Database file name
Browse the file name. This is the location where your database is stored. i.e. – (C:\Users\Authentic\Documents\Database1.accdb).
How To Add Ms Access Database To Visual Studio 2010 – Connection String Database File Name
How To Add Ms Access Database To Visual Studio 2010 – Test Microsoft Access Database Connection
If You want to get database connection string and other database properties go to “Advanced”.
This is the connection string you will use programmatically to connect to ms access database.
How To Add Ms Access Database To Visual Studio 2010 – Provider And DataSource Connection String
Now go to server explorer window and you will see the newly added database.
How To Add Ms Access Database To Visual Studio 2010 – Microsoft Access Database Added To Project Server Explorer
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #3 – How To Add Ms Access Database To Visual Studio 2010 (.accdb file)
CODE SNIPPET C#
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #4 – How To Connect To Ms Access Database In C#
When the data is inserted you get a dialog box informing you that the data has been added to ms-access database successfully.
How To Insert Data Into Ms Access Database Using C Sharp And Display In Datagridview
When you click OK button on the message box, the box closes and datagridview refreshes with a new inserted row at the bottom.
How To Display Data In Datagridview From Access Database C Sharp
All fields are inserted to ms access database at once when you click insert button. The image from picturebox is added to the database as byte array. The Id Column, Which is the first one, Is Auto
Incremented whenever you insert a new row to the database.
CODE SNIPPET C#
try
{
OleDbCommand insertOleDbCommand = new OleDbCommand(insertQuery, accessDatabaseConnection);
insertOleDbCommand.Parameters.AddWithValue("@FullName", OleDbType.VarChar).Value = txtFullName.Text;
insertOleDbCommand.Parameters.AddWithValue("@EmailAddress", OleDbType.VarChar).Value = txtEmail.Text;
insertOleDbCommand.Parameters.AddWithValue("@PhoneNumberP", OleDbType.VarChar).Value = txtPhoneNumber.Text;
insertOleDbCommand.Parameters.AddWithValue("@LanguageP", OleDbType.VarChar).Value = txtLanguage.Text;
insertOleDbCommand.Parameters.AddWithValue("@CountryP", OleDbType.VarChar).Value = txtCountry.Text;
insertOleDbCommand.Parameters.AddWithValue("@GenderP", OleDbType.VarChar).Value = txtGender.Text;
insertOleDbCommand.Parameters.AddWithValue("@ImagePath", OleDbType.VarChar).Value = txtImagePath.Text;
insertOleDbCommand.Parameters.AddWithValue("@ImageFile", OleDbType.Binary).Value = convertImageToByteArray(pictureBox1.Image);
//Opening Access Database Connection
accessDatabaseConnection.Open();
int insertDataToAccessDatabase = insertOleDbCommand.ExecuteNonQuery();
//If data Has been inserted to the database output the following message
if (insertDataToAccessDatabase > 0)
{
MessageBox.Show("Data Inserted To MS-Access Database Susccessfully.........");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #5 – How To Insert Data And Images Into Microsoft Access Database
All rows form ms-access database are displayed in datagridview when you run the application. The first row which is (ID) is not displayed. Image row is the last one. It displays images which are
converted(cast) explicitly to byte array. The Code runs inside form load event.
CODE SNIPPET C#
//Function for retrieving data from ms access database and displaying it on DataGridView
public void populateDataGridView()
{
//First, clear all rows before populating datagridview with data from MS Access Database. Check if datagridview rows are empty before clearing.
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.Rows.Clear();
}
try
{
accessDatabaseConnection.Open();
//OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, acceddDatabaseConnection);
OleDbCommand command = new OleDbCommand(selectDataFromMSAccessDatabaseQuery, accessDatabaseConnection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[8].GetType());
dataGridView1.Rows.Add(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader[5].ToString(), reader[6].ToString(), reader[7].ToString(), (byte[])reader[8]);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #6 – How To Display Data And Images In Datagridview From Microsoft Access On Form Load
The data is updated based on the selected datagridview row ID. To use update feature click on datagridview row, And the input fields gets filled with selected datagridview row data. Then change few
fields and click update button.
CODE SNIPPET C#
private void button1_Click(object sender, EventArgs e)
{
if (txtID.Text == String.Empty)
{
MessageBox.Show("First Click On DatagridView Row Cell Or Make Sure ID Field Is Not Empty.......");
}
else
{
try
{
//Check If One Or More Fields Are Empty
if (txtFullName.Text == String.Empty || txtEmail.Text == String.Empty || txtPhoneNumber.Text == String.Empty || txtLanguage.Text == String.Empty || txtCountry.Text == String.Empty || txtGender.Text == String.Empty || txtImagePath.Text == String.
Empty || pictureBox1.Image == null)
{
MessageBox.Show("One Or More Empty Field Make sure all fields are filled............");
}
else
{
OleDbCommand updateDataInMSAccessDatabaseOleDbCommand = new OleDbCommand(updateDataInMSAccessDatabaseQuery, accessDatabaseConnection);
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@FullName", OleDbType.VarChar).Value = txtFullName.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@EmailAddress", OleDbType.VarChar).Value = txtEmail.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@PhoneNumberP", OleDbType.VarChar).Value = txtPhoneNumber.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@LanguageP", OleDbType.VarChar).Value = txtLanguage.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@CountryP", OleDbType.VarChar).Value = txtCountry.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@GenderP", OleDbType.VarChar).Value = txtGender.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@ImagePath", OleDbType.VarChar).Value = txtImagePath.Text;
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@ImageFile", OleDbType.Binary).Value = convertImageToByteArray(pictureBox1.Image);
updateDataInMSAccessDatabaseOleDbCommand.Parameters.AddWithValue("@ID", OleDbType.Binary).Value = Convert.ToInt32(txtID.Text);
//Opening Access Database Connection
accessDatabaseConnection.Open();
int insertDataToAccessDatabase = updateDataInMSAccessDatabaseOleDbCommand.ExecuteNonQuery();
//If data Has been inserted to the database output the following message
if (insertDataToAccessDatabase > 0)
{
MessageBox.Show("Data Updated In MS-Access Database Susccessfully.........");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
}
//Refreshing Datagridview after Updating a row
populateDataGridView();
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #7 – How To Update Selected Datagridview Row With Textbox And Picture Box
Deleting Selected Rows From Datagridview And Microsoft Access Database In C# Visual Studio
How To Delete Record From Ms-access Database And Datagridview In C Sharp
Then a Message Box Appears showing that the selected row has been deleted successfully.
How To Delete Record From Ms-access Database And Datagridview In C Sharp Windows Application
The Row Gets deleted when you click Delete button. This removes selected row from both MS Access Database and Datagridview.
CODE SNIPPET C#
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
}
//Refreshing Datagridview after Deleting a row
populateDataGridView();
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #8 – How To Delete Selected Rows From Datagridview And Microsoft Access Database
CODE SNIPPET C#
VIDEO TUTORIAL
CODE SNIPPET C#
return Image.FromStream(ms);
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #10 – How To Convert Byte Array To Image
When you click choose image button the Dialog open giving you an option to choose image from your computer. When you choose image and click open button the image is displayed on PictureBox
ready to be inserted into the database. Also full image path is displayed in the appropriate TextBox.
CODE SNIPPET C#
if (chooseImageDialog == DialogResult.OK)
{
txtImagePath.Text = chooseImage.FileName;
//Displaying image from Pc On PictureBox
pictureBox1.Image = Image.FromFile(chooseImage.FileName);
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #11 – How To Choose Image From Computer And Display It On Picturebox
How To Display Selected Row Text And Image From Datagridview To Picturebox And Text Boxes In C Sharp
Each Cell content From a specific row get assigned to appropriate textbox.Text Value when you click on datagridview cell.
CODE SNIPPET C#
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #12 – How To Display Selected Row From Datagridview To Textboxes On Cell Click
How To Display Selected Row Text And Image From Datagridview To Picturebox And Text Boxes In C Sharp
First i had to cast the image from datagridview cell to byte array and then converted it to Image and finally assigned it to picturebox.Image Value.
CODE SNIPPET C#
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #13 – How To Display Selected Row From Datagridview To Picturebox Cell Click
All input fields(textboxes, picturebox) gets cleared when you click Clear button.
CODE SNIPPET C#
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #14 – How To Clear Input Fields Text Boxes And Picture Box
Adding Microsoft Office Interop Excel – Select the Dot NET tab
Click Ok.
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #15 – How To Add Microsoft Office Interop Excel Reference In Visual Studio 2010
The data is exported to excel file when you click export button, Also The dialog box appears prompting you to enter excel file name and select save location.
CODE SNIPPET C#
private void btnExportDataGridViewToExcel_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel._Application exportDataGridViewToExcelApplication = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook exportDataGridViewToExcelWorkbook = exportDataGridViewToExcelApplication.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet exportDataGridViewToExcelWorksheet = null;
exportDataGridViewToExcelApplication.Visible = true;
exportDataGridViewToExcelWorksheet = exportDataGridViewToExcelWorkbook.Sheets["Sheet1"];
exportDataGridViewToExcelWorksheet = exportDataGridViewToExcelWorkbook.ActiveSheet;
exportDataGridViewToExcelWorksheet.Name = "Records";
try
{
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
{
exportDataGridViewToExcelWorksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
exportDataGridViewToExcelWorksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
else
{
exportDataGridViewToExcelWorksheet.Cells[i + 2, j + 1] = "";
}
}
}
if (exportDataGridViewToExcelSaveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
exportDataGridViewToExcelWorkbook.SaveAs(exportDataGridViewToExcelSaveDialog.FileName);
MessageBox.Show("DataGridView Exported To Excel File Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//Release Resources
exportDataGridViewToExcelWorksheet = null;
exportDataGridViewToExcelWorkbook.Close();
exportDataGridViewToExcelApplication.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #17 – How To Export Datagridview To Excel File In C# Windows Application
Excel File gets imported to datagridview when you click Import Button. You can clear datagridview rows before importing to see this feature in Action.
CODE SNIPPET C#
if (importExcelToDataGridViewDialogResult == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Workbook importExcelToDataGridViewWorkbook = importExcelToDataGridViewApplication.Workbooks.Open(importExcelToDataGridViewOpenFileDialog.FileName);
Microsoft.Office.Interop.Excel.Worksheet importExcelToDataGridViewWorksheet = importExcelToDataGridViewWorkbook.ActiveSheet;
ShtRange = importExcelToDataGridViewWorksheet.UsedRange;
//Looping Through excel Cells
for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
{
//Getting Image From excel path cells
Image imageFromExcel = Image.FromFile(importExcelToDataGridViewWorksheet.Cells[Rnum, 8].Value);
//Converting Image To Byte Array
byte[] byteImageFromExcel = convertImageToByteArray(imageFromExcel);
//Populating DataGridView From Excel
dataGridView1.Rows.Add(importExcelToDataGridViewWorksheet.Cells[Rnum, 1].Value, importExcelToDataGridViewWorksheet.Cells[Rnum, 2].Value, importExcelToDataGridViewWorksheet.Cells[Rnum, 3].Value, importExcelToDataGridView
Worksheet.Cells[Rnum, 4].Value, importExcelToDataGridViewWorksheet.Cells[Rnum, 5].Value, importExcelToDataGridViewWorksheet.Cells[Rnum, 6].Value, importExcelToDataGridViewWorksheet.Cells[Rnum, 7].Value, importExcelToDataGridViewWorkshe
et.Cells[Rnum, 8].Value, byteImageFromExcel);
}
//Release Resources
importExcelToDataGridViewWorkbook.Close();
importExcelToDataGridViewApplication.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally {
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #16 – How To Import Excel File To Datagridview In C# Windows Application
To print DataGridView Drag PrintDocument from toolbox to your form application. As Show Below.
How To Print Datagridview In C Sharp – Drag PrintDocument from toolbox to your form application
CODE SNIPPET C#
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
dataGridView1.DrawToBitmap(bm, new System.Drawing.Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
e.Graphics.DrawImage(bm, 0, 0);
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #18 – How To Print Datagridview In C# Windows Application
First am checking if the DataGridView rows are empty before clearing them.
CODE SNIPPET C#
private void btnclearDataGridView_Click(object sender, EventArgs e)
{
//Checking if datagridview rows are empty before clearing data
if (dataGridView1.Rows.Count > 0 )
{
//Clear All Rows
dataGridView1.Rows.Clear();
}
else
{
MessageBox.Show("DataGridView Is Empty.. ");
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #19 – How To Clear Datagridview In C# Windows Application
Clearing rows from the datagridview doesn’t delete them from MS Access. Thus, Refreshing it restore cleared rows.
Refresh Feature calls populateDataGridView Function, which populates datagridview with data from MS Access Database.
CODE SNIPPET C#
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #20 – How To Refresh Datagridview In C# Windows Application
How To Show Selected Datagridview Row Data In Another Form In C# Windows Application
CODE SNIPPET C#
private void btnViewSelectedRowOnNewForm_Click(object sender, EventArgs e)
{
}
else
{
MessageBox.Show("Unknown Error Try Again......");
}
}
VIDEO TUTORIAL
C# And Ms Access Database Tutorial #21 – How To Show Datagridview Selected Row Data In Another Form Using C#
How To Show Datagridview Selected Rows Data In Another Forms Datagridview In C# Windows Application
How To Show Datagridview Selected Rows Data In Another Form Datagridview
CODE SNIPPET C#
}
showDatagridviewSelectedRowsDataInAnotherFormDatagridview.ShowDialog();
}
else if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("DataGridView Is Empty......");
}
else if (dataGridView1.SelectedRows.Count == 0 && dataGridView1.Rows.Count > 0)
{
MessageBox.Show("DataGridView Has Data But There Is No Row Selected......");
}
else
{
MessageBox.Show("Unknown Error Try Again......");
}
}
C# And Ms Access Database Tutorial #22 – How To Show Datagridview Selected Rows To Another Forms Datagridview Using C#
DEMO VIDEO
How To Connect To Ms Access Database Insert Update Delete Clear Print Export Import Excel Display In DatagridView In C# Windows Application (Demo Video)
(CRUD) C# And Microsoft Access Database Tutorial – Insert Update Delete Select And Display On DataGridView Complete Project Guide Using Visual Studio 2010
Tags: access database, Clear, CRUD, Database, datagridview, delete, Display, edit, Excel, Export, Exporting Datagridview to Excel in C Sharp, how to add column in datagridview in c#, how to add row in datagridview in c#, how to
clear datagridview in c# on button click, how to connect ms access database, How To Connect To Access Database And Display Data And Images On Datagridview In C# Windows Application
, How To Create Ms Access
Database, how to delete data from ms access database using c#.net, how to display data from ms access database using c#.net, how to export datagridview to excel in c#, how to extract data from ms access database, how to
fetch data from ms access database in c#, how to filter datagridview in c#, how to get data from ms access database in c#, how to insert data into ms access database using c#, how to print datagridview in c#, how to read data
from ms access database in c#, how to refresh datagridview in c#, How To Refresh Datagridview In C# Windows Application, how to retrieve data from ms access database in c#, how to save and load images from access
database using C#, how to select data from ms access database using c#.net, how to show data in datagridview in c#, how to update data into ms access database using c#.net, how to update datagridview in c#, Import, Insert,
Insert Image Into Database, microsoft access, print, Refresh, Saving & Reading Images from database, tutorial, Update
Published by admin
View all posts by admin
Prev
Solved!! Can’t read from the source file or disk. [Problem Fixed]
Next
How To Add And Use Images From Resources In C Sharp Using Visual Studio 2010
Leave a Reply
Your email address will not be published. Required fields are marked *
Comment
Name *
Email *
Website
Save my name, email, and website in this browser for the next time I comment.
POST COMMENT