Thursday, July 13, 2006

Creating DataGrid Dynamically with C#

Here is a very simple and easy way to create a DataGrid dynamically and showing some data in it.

1. Create a function in your code file as CreateDataGrid() and use this code in it


public void CreateDataGrid()
{
//declare datagrid and properties
DataGrid DataGrid1 = new DataGrid();
DataGrid1.BorderWidth = Unit.Pixel(3);
DataGrid1.CellPadding = 12;
DataGrid1.GridLines = GridLines.Both;
DataGrid1.BorderColor = Color.Black;
DataGrid1.ShowHeader = true;
DataGrid1.HeaderStyle.BackColor = Color.Pink;
DataGrid1.HeaderStyle.Font.Bold = true;
DataGrid1.AutoGenerateColumns = false;
DataGrid1.SelectedItemStyle.BackColor = Color.LightBlue;
//columns for grid
BoundColumn dgcol = new BoundColumn();
dgcol.HeaderText = "Last Name";
dgcol.DataField = "lastname";
DataGrid1.Columns.Add(dgcol);
dgcol = new BoundColumn();
dgcol.HeaderText = "First Name";
dgcol.DataField = "firstname";
DataGrid1.Columns.Add(dgcol);
dgcol = new BoundColumn();
dgcol.HeaderText = "DOB";
dgcol.DataField = "BirthDate";
dgcol.DataFormatString = "{0:d}";
DataGrid1.Columns.Add(dgcol);
//add event handlers
DataGrid1.SelectedIndexChanged += new EventHandler(DataGrid1_SelectedIndexChanged);
//bind datagrid
DataGrid1.DataSource = GetDataSource();
DataGrid1.DataBind();
//add datagrid to the page
Page.Controls.Add(DataGrid1);
}


2. add event handler for your grid.

private void DataGrid1_SelectedIndexChanged(object sender, EventArgs e)
{
//your event code here
}


3. link the datagrid with data source create a function which return dataset.

protected DataSet GetDataSource()
{
OleDbConnection con;
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da;
DataSet ds = new DataSet();
string sSQL = "select lastname,firstname,birthdate from employees";
// Change Data Source to the location of Northwind.mdb on your local system.
string sConStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Northwind.mdb; User Id=admin; Password=";
con = new OleDbConnection(sConStr);
da = new OleDbDataAdapter(sSQL, con);
da.Fill(ds, "employees");
return ds;
}

4. finally call the CreateDataGrid() function from your Page_load.

please leave comments if its help.

0 Comments:

Post a Comment

<< Home