Hi dibyaaryan007,
If you are not sure where to add a new column to the grid, then I wold suggest you to use below class to create a TemplateField in your gridview. Please look at the below code for example.
public class DynamicGridViewTextTemplate : ITemplate
{
string _ColName;
DataControlRowType _rowType;
int _Count;
public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
{
_ColName = ColName;
_rowType = RowType;
}
public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)
{
_rowType = RowType;
_Count = ArticleCount;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Label lc = new Label();
lc.Text = _ColName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.lbl_DataBind);
container.Controls.Add(lbl);
break;
case DataControlRowType.Footer:
Label flc = new Label();
container.Controls.Add(flc);
break;
default:
break;
}
}
private void lbl_DataBind(Object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridViewRow row = (GridViewRow)lbl.NamingContainer;
lbl.Text = DataBinder.Eval(row.DataItem, _ColName).ToString();
}
}
Then below code is used to add a column to the grid before binding the data.
private void AddColumns(DataTable dt)
{
TemplateField tf;
for (int i = 0; i < dt.Rows.Count; i++)
{
tf = new TemplateField();
tf.HeaderText = "Col Header";
tf.HeaderTemplate = new DynamicGridViewTextTemplate(Convert.ToString(dt.Rows[i][0]), DataControlRowType.Header);
tf.HeaderStyle.CssClass = "gridHeader";
tf.ItemTemplate = new DynamicGridViewTextTemplate(Convert.ToString(dt.Rows[i][0]), DataControlRowType.DataRow);
gridView.Columns.Insert(XXXX, tf);
}
}
XXXX specifies the column number at which the new dynamic column has to be added.
Please go through the code for a better understanding. For this to be achieved, you've make the viewstate as false for the gridview (EnableViewState="false").
Thank you,
Vamsi