This code snippet show you how to add grid view columns by programmatically but nor actually by the design.
ASPX
<asp:GridView ID="Grid" runat="server" Width="100%" AutoGenerateColumns="False" OnInit="Grid_Init">
<HeaderStyle CssClass="spn_gridheader" />
<RowStyle CssClass="spn_gridrow" />
<PagerStyle HorizontalAlign="Right" ForeColor="#009900" VerticalAlign="Middle" />
</asp:GridView>
ASPX.CS
At grid view initialization,
protected void Grid_Init(object sender, EventArgs e)
{
Grid.AutoGenerateColumns = false;
Grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
BoundField date = CreateBoundField("Date","Header name","format"}");
BoundField month = CreateBoundField("Month","Header name","format"}");
BoundField year = CreateBoundField("Year","Header name","format"}");
//Styling header columns
date.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
month.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
year.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
Grid.Columns.Add(date);
Grid.Columns.Add(activity);
Grid.Columns.Add(paid);
}
private static BoundField CreateBoundField(string dataField, string header, string dataFormatString)
{
BoundField field = new BoundField();
field.DataField = dataField;
field.HeaderText = header;
if (!dataFormatString.Equals(""))
{
field.DataFormatString = dataFormatString;
}
field.SortExpression = dataField;
field.HtmlEncode = false;
return field;
}
Addition:
You can add image column also if you want by using the Grid_RowDataBound event.
protected void GridViewRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton Button = new ImageButton();
Button.ID = "actionNoteButton";
Button.ImageUrl = ResolveUrl("imagepath.jpg");
e.Row.Cells[column index].Controls.Add(Button);
}
}
cheers!
No comments:
Post a Comment