Dynamically adding rows and columns to Grid View

Hi to add rows and columns to Gridveiw dynamically what
we will do is that

1) Create a DataTable object to which than we will bind the GridView
DataTable dt=new DataTable();

2) IF you need two columns than create two DataColumn object
DataColumn dCol1=new DataColumn(FirstC, typeof(System.String)); // string FirstC=”column1″
DataColumn dCol2=new DataColumn(SecondC, typeof(System.String)); // string SecondC=”column2″

Add it to the table

dt.Columns.Add(dCol1);
dt.Columns.Add(dCol2);

3)Run the loop for as many rows you want to add.

// say you want to add two rows

for(int i=0;i<2;i++)
{
DataRow row1 = dt.NewRow();
row1 [FirstC] = “One”;
row1 [SecondC] =”Two”
dt.Rows.Add(row1 );

}

Now iterate through each datacolumn and create a BoundField foreach column

foreach (DataColumn col in dt.Columns)
{
BoundField bField = new BoundField
bField.DataField = col.ColumnName;
bField.HeaderText = col.ColumnName;
GridView1.Columns.Add(bField);
}
GridView1.DataSource = dt;
//Bind the datatable with the GridView.
GridView1.DataBind();

Advertisements

Internal Access Modifier in C#

In C#
The internal access modifier can be applied to
Classes and it’s member
Structure and it’s member
Enumeration
Interface

This way it is available to all the files within that assembly.
Particularly useful when creating software components.

It can be used in conjunction with protected to produce
protected internal access modifier
It can be applied only to
Class members

It is available withing it’s own assembly or to derived types.

For e.g.

Say if we create an Class Library which has a class like

namespace ClassLibrary1
{
public class MyClass

……

And then you create

Now we create new project say a windows application and add a refrence to that dll
And can create the object of that class lik

MyClass my=new MyClass();

this works fine,

now if we modify the definition of the class by replacing public with internal and update the assembly

namespace ClassLibrary1{
internal class MyClass

This time if we try to create the object of MyClass which is inside our referenced assembly
The error which we will get is

MyClass is inaccessible due to its protection level.

That’s why they are basically used in component development so that any other class couldn’t be able to access it i.e. create objects of it.

That’s it