Insert,update,delete using generic list

Insert,update,delete using Generic list

Create a windows form project drag a datagrid view and place two textbox and name it as name,mobile
place three buttons namely insert,update,delete

In the variable decleration, create a generic array list

List contacts;

In the form load create a object for the list

Add columns name,mobile to datagrid view, for insert,update, delete you can use the code below



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace GenericList
{
public partial class frmContact : Form
{
List contacts;
public frmContact()
{
InitializeComponent();
}

# region Insert Operation
private void btnInsert_Click(object sender, EventArgs e)
{
Contact cnt = new Contact();
cnt.Name = txtName.Text.Trim();
cnt.Mobile = txtMobile.Text.Trim();
contacts.Add(cnt);
CurrencyManager cm = (CurrencyManager)this.BindingContext[contacts];
cm.Refresh();
dgcontacts.DataSource = contacts;
}
# endregion

#region Update Operation

private void btnUpdate_Click(object sender, EventArgs e)
{
List select = contacts.FindAll(new Predicate(HasName));
if (select.Count > 0) // record found
{
foreach (Contact cnt in select)
{
cnt.Name = txtName.Text.Trim();
cnt.Mobile = txtMobile.Text.Trim();
}
CurrencyManager cm = (CurrencyManager)this.BindingContext[contacts];
cm.Refresh();
dgcontacts.DataSource = contacts;

}
else
{
MessageBox.Show("No records found");
}
}

# endregion

//This function will check for the person name
bool HasName(Contact c)
{
return (c.Name == txtName.Text);
}

# region Delete Operation

private void btnDelete_Click(object sender, EventArgs e)
{
List select = contacts.FindAll(new Predicate(HasName));
if (select.Count > 0) // record found
{
foreach (Contact cnt in select)
{
contacts.Remove(cnt);
}
CurrencyManager cm = (CurrencyManager)this.BindingContext[contacts];
cm.Refresh();
dgcontacts.DataSource = contacts;

}
else
{
MessageBox.Show("No records found");
}

}

# endregion

private void dgcontacts_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
}

private void frmContact_Load(object sender, EventArgs e)
{
contacts = new List();
}
}

//Contact Class
public class Contact
{
private string _Name;
private string _Mobile;

public string Name
{
get { return _Name; }
set { _Name = value; }
}

public string Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
}
}


Comments

Guest Author: Alena20 Feb 2012

Good job mkanig it appear easy.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: