Powered By Blogger

Monday, November 9, 2009

Dynamic Datatable in C#

Create DataTable Dynamically using C#

DataTable DT = new DataTable();


//Create Column

DT.Columns.Add("Column 1");
DT.Columns.Add("Column 2");
DT.Columns.Add("Column 3");

//End Column

//Create and Add New Row

DataRow DTRow= DT.NewRow();

//Inserting values to each cell in a row

DTRow[0] = "First cell";
DTRow[1] = "Second cell";
DTRow[2] = "Third cell";

DT.Rows.Add(DTRow);

DataReader and Dataset

  • A DataReader works in a connected environment, whereas DataSet works in a disconnected environment.
  • Dataset communicates with the dataadapter only whereas datareader communicates with the command object
  • Dataset supports integeration with XML whereas Datareader doesn't support.
  • We can create relations in dataset whereas we can't create relation in datareader.
  • Dataset is scrollable whereas datareader is forward only record set.
DataReader :

A DataReader object represents a forward only, read only access to data from a source.

It will require you to open the connection through out and so it is not suitable for
interacting between different tiers.



Dataset:

DataSet is disconnected, in-memory representation of relational database.

It is well suited to communicate remotely as it is disconnected and changes
can be updated whenever it is required.




Fill gridview using Datareader:

SqlConnection con = new SqlConnection("server=.;database=northwind;integrated security=true");
SqlCommand com = new SqlCommand("select * from Categories", con);
SqlDataReader DR;
con.Open();
DR = com.ExecuteReader(CommandBehavior.CloseConnection);
DR.Read();
GridView1.DataSource = DR;
GridView1.DataBind();


Fill gridview using DataSet:

SqlConnection con = new SqlConnection("server=.;database=northwind;integrated security=true");
SqlDataAdapter DA = new SqlDataAdapter("select * from Categories", con);
DataSet DS = new DataSet();
DA.Fill(DS);
GridView1.DataSource = DS;
GridView1.DataBind();

openFileDialog c#

OpenFileDialog openFileDialogX = new OpenFileDialog();
string Fname, Fext,fpath ;
int Fsize;

private void GetOpenFileDialog()
{
openFileDialogX.CheckPathExists = true;
openFileDialogX.Filter = "Image Files (*.bmp;*.jpg;*.jpeg)|*.bmp;*.jpg;*.jpeg|" + "PNG files (*.png)|*.png|text files (*.text)|*.txt|doc files (*.doc)|*.doc|pdf files (*.pdf)|*.pdf|excel files(*.xls)|*.xls|excel files07(*.xlsx)|*.xlsx";
openFileDialogX.Multiselect = false;
openFileDialogX.AddExtension = true;
openFileDialogX.ValidateNames = true;
openFileDialogX.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
openFileDialogX.ShowDialog();
fpath = openFileDialogX.FileName.ToString();
fname=System.IO.Path.GetFileName(openFileDialogX.FileName).ToUpper();
Fsize = openFileDialogX.FileName.Length;
Fext = System.IO.Path.GetExtension(Fname);
}