Click here to Skip to main content
Click here to Skip to main content
Go to top

Database Manipulation with ADO.NET for beginners

, 17 May 2005
Rate this:
Please Sign up or sign in to vote.
Personal address book using ADO.NET and C#.

Sample Image

Introduction

This is the second part of Using ADO.NET for beginners. It is a simple Personal Address Program that returns results from a database table, writes the output to textboxes, and uses buttons (First, Previous, Next, Last) to navigate through the records.

You also can manipulate the data by clicking the toolbar buttons, namely Add/New record, Save the new record, Delete the current record, and Edit/Update the records.

I chose Microsoft Access database (as reflected in the ADO.NET OleDb objects) because it's easy to use and you don't need to have Microsoft SQL Server running. But ADO.NET is highly optimized if you are working with Microsoft SQL Server databases (as reflected in the ADO.NET Sql objects).

How it works?

After getting connected to the MS Access database, all the records will be displayed in the textboxes. In order to navigate through the records, you can use buttons Next, Previous, First, Last. You can find a detailed explanation about the use of the navigation buttons in the first part: Using ADO.NET for beginners.

Insert a new record

If you click the New button in the toolbar, the following methods are invoked:

  • fnEnableToolbarButtons(true, "Save") to enable the "Save" button.
  • fnEnableToolbarButtons(false, "Delete") to disable the "Delete" button.
  • fnEnableToolbarButtons(false, "Edit") to disable the "Edit" button.
  • fnEnableButtonsNextPreviousLastFirst(false) to disable the navigation buttons.
  • fnClearAllTextBox() to clear all the textboxes.
  • fnEnableDisableTextBox(true) to enable the textboxes for editing.

Here are the code snippets of the methods I used for the New button:

Depending on the two parameters of the method called, we enable or disable the ToolbarButton. For example: fnEnableToolbarButtons(true, "Save"); means we check the parameters are "Save" and "true" and enable the "Save" button. If we use "false" instead of "true", we disable the "Save" button.

private void fnEnableToolbarButtons(bool b, string s1) 
{ 
    if (s1=="New") 
      this.toolBarButtonNew.Enabled=b; 
    else if (s1=="Save")
      this.toolBarButtonSave.Enabled=b;
    else if (s1=="Delete")
      this.toolBarButtonDelete.Enabled=b;
    else if (s1=="Edit")
      this.toolBarButtonEdit.Enabled=b;
    else if (s1=="Refresh")
      this.toolBarButtonRefresh.Enabled=b; 
}

The method "fnEnableButtonsNextPreviousLastFirst" has only one bool parameter. In a foreach loop, we iterate through all the controls on the form and check if it's a Button, then enable or disable it with the bool parameter.

public void fnEnableButtonsNextPreviousLastFirst(bool flag) 
{ 
    string str; 
    foreach(Control ctrl in this.Controls) 
    { 
       str = Convert.ToString(ctrl.GetType()); 
       if(str == "System.Windows.Forms.Button")             
          ctrl.Enabled = flag;
    }
}

In the method "fnClearAllTextBox()", we iterate through all the controls on the form and check if it is a TextBox, then we clear the contents of the TextBox.

private void fnClearAllTextBox() 
{ 
   string str; 
   foreach(Control ctrl in this.Controls)
   { 
     str=Convert.ToString(ctrl.GetType()); 
     if(str=="System.Windows.Forms.TextBox")             
        ctrl.Text = "";
   }
}

public void fnEnableDisableTextBox(bool flag) 
{
   string str; 
   foreach(Control ctrl in this.Controls) 
   { 
      str = Convert.ToString(ctrl.GetType()); 
      if(str == "System.Windows.Forms.TextBox") 
        ctrl.Enabled = flag; 
   }
}

Save the new record

If you click the New button to insert a new record, the Save button will be enabled so that you can save the new record.

The code snippet of the method for the Save a new record is shown here:

private void fnSaveNewRecord() 
{
  try
  {
     string strInsert;
     strInsert = "insert into PersonTable" + 
        "(FirstName, LastName, Title, City,Country)" 
        + " values('" + this.textboxFirstname.Text + "', '"
        + this.textboxLastname.Text + "', '"
        + this.textboxTitle.Text + "', '"
        + this.textboxCity.Text + "', '"
        + this.textboxCountry.Text + "')";
     if (this.textboxFirstname.Text !="" && 
           this.textboxLastname.Text !=""&& 
           this.textboxTitle.Text !="" && 
           this.textboxCity.Text !="" 
           && this.textboxCountry.Text !="") 
     { 
         this.oleDbDataAdapter1.InsertCommand.CommandText = strInsert;
         //do the insert
         this.oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
         //Get the last PersonID from the table and display it in TextBox
         fnGetLastPersonID(); 
         fnEnableButtonsNextPreviousLastFirst(true);
         fnEnableToolbarButtons(true, "Edit"); 
         fnEnableToolbarButtons(true, "Delete"); 
         fnEnableToolbarButtons(false, "Save");
         this.fnEnableDisableTextBox(false); 
     }else 
     {
         MessageBox.Show("You have to fill the TextBoxes...", 
                 "WARNING", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                  this.textboxFirstname.Focus();
     }
  }
  catch (Exception ex)
  {
     MessageBox.Show("Error in inserting new record : " + 
        ex.Message, "Insert Error", MessageBoxButtons.OK, 
        MessageBoxIcon.Information);
     fnRefreshDataSet();
  } //try-catch
}

As you can see, there are some methods to be invoked in the method "fnSaveNewRecord()". One of them is "fnGetLastPersonID()" which gets the last PersonID from the table and displays it in the TextBox "textboxPersonID". After a new record is inserted and the INSERT command executed, I get the new PersonID of the new inserted record.

Here, you should pay attention to how the DataType AutoNumber problem in the table "PersonTable" was solved. I chose a different way for the AutoNumber issue.

First of all, you have to create the SELECT command only for the PersonID column. And then:

  • Execute DataReader and the command with the connection and string command (strCom).
  • Run the while loop and get all values (contents) of the column 0 (GetValue(0)).
  • Store it in an object variable, convert it to integer until the end of the column (0) values.

When the while-loop is finished, you will get the last value in the first column (0) GetValue(0) outside while-loop. Increment the PersonID by 1 and display it in the TextBox "textboxPersonID".

Here is the code of the method "fnGetLastPersonID()":

private void fnGetLastPersonID() 
{
    string strCom = "Select Max(PersonID) from PersonTable" ; 
    OleDbCommand cmd =new OleDbCommand(strCom,this.oleDbConnection1);
    OleDbDataReader reader;
    reader =cmd.ExecuteReader() ;
    int i=0 ; //how many records in the table?, only for test
    int iPersonid=0; //the integer value of the first column(0) contents
    while(reader.Read()) 
    {
       i++ ;
       // GetValue(0) means: The contents
       // of the first column(0)(PersonID) in the table
       object obValue = reader.GetValue(0);
       iPersonid = Convert.ToInt32(obValue.ToString());
    }
    i++ ; 
    this.textboxPersonID.Text=iPersonid.ToString(); //display it in TextBox
    reader.Close(); //close the DataReader otherwise error
    MessageBox.Show("Record with new PersonID: "+iPersonid.ToString()+ 
           " inserted successfully", "Save New", MessageBoxButtons.OK, 
           MessageBoxIcon.Information); //inform the user
}

Delete the current record

The current record is deleted with the help of the method "fnDeleteCurrentRecord()". If the Delete button is clicked, you will be asked whether you want to delete the record or not. If the answer is Yes, the DELETE command will be executed and the method "fnRefreshDataSet()" is invoked.

The code snippet is as follows:

private void fnDeleteCurrentRecord 
{
    DialogResult dr=MessageBox.Show("Are you sure you want to delete" + 
                    " this record ? ", "Confirm deleting", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
     //convert textboxPersonID into integer
    int pid=int.Parse(this.textboxPersonID.Text); 
    if (dr ==DialogResult.Yes)
    {
      string strDel="DELETE FROM PersonTable WHERE PersonID= "+pid;
      fnExecuteQuery(strDel); 
      fnRefreshDataSet(); 
      MessageBox.Show("Record deleted..."); 
    }
    else
      MessageBox.Show("Record NOT deleted..."); 
}

Edit the current record

If you navigate through the records, the current record is disabled to edit in the textboxes. As soon as you click the Edit button, all the textboxes will be enabled to edit, and the Update button will appear in the toolbar so that you can save the current updated record.

this.toolBarButtonNew.Enabled=false; 
this.fnEnableDisableTextBox(true); 
fnSetEditUpdateText("Update");

Here is the method "fnSetEditUpdateText()" which gets a string as parameter:

private void fnSetEditUpdateText(string str)
{
  this.toolBarButtonEdit.Text=str; 
}

Update/Save the edited current record

Here are the methods called if you click the Update button:

fnUpdateRecord(); 
fnSetEditUpdateText("Edit"); 
fnEnableToolbarButtons(true, "New"); 
this.fnEnableDisableTextBox(false);

First, the method "fnUpdateRecord()" is invoked to update the record. Second, the text of the Update button will be changed to "Edit" with the fnSetEditUpdateText("Edit") method. And then the method "fnEnableToolbarButtons(true, "New")" is called to set the "New" button enabled. Lastly, the method "fnEnableDisableTextBox(false)" will be called to disable all the textboxes with the help of the parameter "false".

There you have the code snippet of the method "fnUpdateRecord()":

private void fnUpdateRecord() 
{
  try 
  {
     string strUpdateQuery = "update PersonTable set FirstName='"
    +this.textboxFirstname.Text+"',LastName='"
    +this.textboxLastname.Text+"' ,Title='"
    +this.textboxTitle.Text+"' ,City='"
    +this.textboxCity.Text+"' ,Country='"
    +this.textboxCountry.Text +"' WHERE PersonID= "+this.textboxPersonID.Text;
    fnExecuteQuery(strUpdateQuery);
    fnRefreshDataSet();  
    MessageBox.Show("Record updated..."); 
  }catch(Exception ex) 
  {
     MessageBox.Show(ex.ToString());
  }
}

Refresh/Cancel the rows

With the Refresh button, all the textboxes are set to be disabled to edit. The text of the Update button will be changed to "Edit", Save button is disabled (false), Edit, Delete, and New buttons are enabled (true). With the method "fnEnableButtonsNextPreviousLastFirst(true)", all the navigation buttons (Next, Previous, Last, First) will be enabled. And lastly, the method "fnRefreshDataSet()" is invoked to refresh rows in the DataSet. In other words, the first record is going to be displayed.

Here is the code snippet of the method fnRefreshDataSet():

private void fnRefreshDataSet()
{
  this.dataSet11.Clear(); //clear the contents of dataset 
  this.oleDbDataAdapter1.Fill(this.dataSet11,"PersonTable"); 
}

In conclusion

I hope this is a useful program for your ADO.NET database projects. If you wish, you can add new textboxes (Phone, Fax, Zip code etc.) on the Form to extend the program. I'd be glad to receive any suggestions or comments.

Here is again the link for the first part of this application: Using ADO.NET for beginners.

Good coding!!

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

Share

About the Author

Huseyin Altindag
Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAli Agha17-Sep-13 22:38 
Generalsame problem Pinmembershelton24-Jul-09 4:21 
QuestionC# ADO.NET Pinmemberfanfanata_cobra21-Oct-08 6:50 
AnswerRe: C# ADO.NET PinmemberRaviRanjankr1-Mar-11 21:59 
GeneralGood one PinmemberJPandya6-Jul-07 8:58 
Generalrelational path Pinmembercouter4-Jun-07 4:50 
GeneralNo bound controls PinmemberJeenajeena23-May-07 5:11 
GeneralDataset is updated but not the database table PinmemberNeroToxic27-Mar-07 0:55 
GeneralRe: Dataset is updated but not the database table PinmemberIslam91-Apr-07 8:27 
GeneralRe: Dataset is updated but not the database table PinmemberNeroToxic1-Apr-07 21:19 
GeneralRe: Dataset is updated but not the database table PinmemberIslam92-Apr-07 15:03 
GeneralHi Pinmemberanil7519-Oct-06 8:35 
Generalother toolbar Pinmembersohailalikhan19-Aug-06 0:14 
Generalcode source Pinmemberjoe101025-Apr-06 15:37 
GeneralPanel PinmemberPawel_gg20-Aug-05 19:19 
GeneralRe: Panel PinmemberHuseyin Altindag23-Aug-05 4:28 
GeneralOn deleting records. PinmemberJerry Walter10-May-05 6:22 
GeneralRe: On deleting records. PinmemberHuseyin Altindag15-May-05 7:31 
Generalnewperfect Pinmemberkritbodin3-Mar-05 15:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 17 May 2005
Article Copyright 2005 by Huseyin Altindag
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid