Search

Custom Search

Wednesday, September 24, 2008

CollectionBase in C#

In order to bind a collection to a data source we must implement ICollection and IEnumerable. For directly inheriting these interfaces we have to implement several functions, some of them may not be useful. By deriving from the abstract class CollectionBase we automatically derive ICollection and IEnumerable.

Sample program given below will illustrate the use of CollectionBase

Create a new project in C#, give the name as CollectionBaseDemo and save it to your sample folder. Add a class module to your project and paste the code given below.

using System;
using System.Collections;
using System.Text;

namespace MyCollectionBase
{
public class Product
{
int mintID;
string mstrItemName;
double mdblRate;

public int ID
{
get
{
return (mintID);
}
set
{
mintID = value;
}
}
public string ItemName
{
get
{
return (mstrItemName);
}
set
{
mstrItemName = value;
}
}
public double Rate
{
get
{
return (mdblRate );
}
set
{
mdblRate = value;
}
}
}

public class Products : CollectionBase
{
public Product this[int index]
{
get
{
return (Product )this.List[index];
}
set
{
this.List[index] = value;
}
}

public void Add(Product product)
{
this.List.Add(product);
}

public void Remove(Product product)
{
this.List.Remove(product);
}
}
}


Create a form and name it as frmSample.cs and design it as given in the Fig. given below.



Give the name of buttons as btnAdd, btnRemove and btnShow, button1.
Name of combobox should be cboItems.



Take the code window of form and paste the code below.

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

namespace MyCollectionBase
{
public partial class frmSample : Form
{
Products objProducts =null;

public frmSample()
{
InitializeComponent();

objProducts = new Products();

}

private void btnAdd_Click(object sender, EventArgs e)
{
Product objItem = new Product();


objItem.ID = Convert.ToInt32 (textBox1.Text.ToString());
objItem.ItemName = textBox2.Text.ToString();
objItem.Rate = Convert.ToDouble (textBox3.Text.ToString());

objProducts.Add(objItem);
}

private void btnShow_Click(object sender, EventArgs e)
{
int intIndex=0;
try
{
intIndex = Convert.ToInt32(textBox1.Text.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Product objItem = new Product();

objItem = objProducts[intIndex];
if (objItem != null)
{
textBox2.Text = objItem.ItemName;
textBox3.Text = objItem.Rate.ToString();
}
}


private void btnRemove_Click(object sender, EventArgs e)
{
int intIndex=0;
try
{
intIndex = Convert.ToInt32(textBox1.Text.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Product objItem = new Product();

objItem = objProducts[intIndex];

if (objItem != null)
{
objProducts.Remove(objItem);
MessageBox.Show("Item Removed");
}
}

private void button1_Click(object sender, EventArgs e)
{
try
{
cboItems.ValueMember = "ID";
cboItems.DisplayMember = "ItemName";
cboItems.DataSource = objProducts;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

Tuesday, September 9, 2008

ADO.net Simplified

How to open a connection using ADO.net?

To use ADO.net connection object, add System.data namespace and for using connection with databases other than SQL Server use System.data.Oledb.

Let us see how to generate a connection string for accessing a access database Sales.mdb, which is located in d:\Sales path.

using system;
using system.data;
using system.data.Oledb;

private OleDBConnection OpenConnection()
{
string strConnection = "Provider=Microsoft.Jet.OleDb.4.0;";
strConnection += @"Data Source=C:\Sales\Sales.mdb”;
strConnection +=@"Persist Security Info=False;";

OleDbConnection objConnection = new OleDbConnection(strConnection);

objConnection.Open();
if(objConnection.IsOpen()))
{
Messagebox.Show(“Connection Opened”);
}
objConnection.Close();
}

How to use dataReader in C#?

DataReader in C# is used to read data from a table. This is a faster way of accessing data from a table. When you want to generate reports use this object.

OleDbCommand command = new OleDbCommand();
command.Connection = Connection;
command.CommandText = "SELECT * FROM Items";

OleDbDataReader dataReader;
dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

How to read data from a dataReader?

int nFields = dataReader.FieldCount;
while (dataReader.Read())
{
String [] subitems = new String[nFields];
for (int i = 0; i < nFields; i++)
{
subitems[i] = dataReader[i].ToString();
}

}
dataReader.Close();



How to use a dataset to display data in a Grid?

string strSQL = "SELECT ID, description FROM items";
DataSet objDataSet = new DataSet();
OleDbConnection objConnection = new OleDbConnection(strConnection);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConnection);
objAdapter.Fill(objDataSet, "Items");
DataView objDataView = new DataView(objDataSet.Tables["Items"]);
dgNameList.DataSource=objDataView;
dgNameList.DataBind();

How to use a Command object to insert records into a table?

String sSQLCommand = "INSERT INTO Person (Age, FirstName, Description, Updated) " +
"VALUES( 55, 'Bob', 'Is a Penguin', '2001/12/25 20:30:15' );";

ADOCommand cmdAdder = new ADOCommand(sSQLCommand, DB_CONN_STRING);
cmdAdder.ActiveConnection.Open();

int nNoAdded = cmdAdder.ExecuteNonQuery();

Updating a table using command object

String sSQLCommand = "UPDATE Items SET Rate = 27 WHERE Description = Jaya Rice";

Deleting a record using command object

String sSQLCommand = "DELETE FROM items WHERE Description = Jaya Rice";