Tuesday, July 03, 2007

Add New Row to a Grid View

Adding new row to a grid view, offcourse with a post back is pretty simple. All u have to have is atlas tool installed, ie ajax extender tool installed.
Drag a Update panel from ajax tool kit and drop ur grid view on the same. Update panel feature is that, post back shall happen with only the panel controls and seems like there was actually no post back at all.

Code below is the example which clearly explains update panel :)

ASPX page
<_body>
<_form id="form1" runat="server">
<_asp:scriptmanager id="ScriptManager2" runat="server">
<_asp:updatepanel runat="server" id="UpdatePanel1" updatemode="Conditional"> <_contenttemplate>
<_div style="background-color: Lime; width: 100px;">
<_asp:label id="PartialPostBackLabel" runat="server">
<_asp:button id="PartialPostBackButton" runat="server" text="Partial Post Back" onclick="PartialPostBackButton_OnClick">

<_asp:gridview id="grdvShortTermFTRs" runat="server" autogeneratecolumns="False" pagesize="5" showfooter="True">
<_columns>
<_asp:hyperlinkfield headertext="FTR No." text="Testing" datatextfield="test1" datanavigateurlfields="test1" datanavigateurlformatstring="~/Default.aspx?FTRNo={0}">
<_itemstyle width="75px">

<_asp:boundfield headertext="Employee No." datafield="test2"> <_itemstyle width="75px">

<_asp:boundfield headertext="Name" datafield="test3">
<_itemstyle width="125px"> <_asp:boundfield headertext="Country" datafield="test4">
<_itemstyle width="75px">


Code Behind
public partial class Default2 : System.Web.UI.Page
{
public static int intRowCount;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ intRowCount = 3; bindGridView();
}
}
protected void bindGridView()
{
DataTable dt = new DataTable();
DataColumn testcolumn1 = new DataColumn("test1");
DataColumn testcolumn2 = new DataColumn("test2");
DataColumn testcolumn3 = new DataColumn("test3");
DataColumn testcolumn4 = new DataColumn("test4");

dt.Columns.Add(testcolumn1); dt.Columns.Add(testcolumn2); dt.Columns.Add(testcolumn3); dt.Columns.Add(testcolumn4);
for (int i = 0; i < intRowCount; i++)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
grdvShortTermFTRs.DataSource = dt;
grdvShortTermFTRs.DataBind();
}
protected void PartialPostBackButton_OnClick(object sender, EventArgs e)
{
intRowCount++; bindGridView();
}
}

No comments: