Appending DataTable Values into Gridview At Runtime Using ASP.Net
June 21, 2012 Leave a comment
Hi Friends,
Today my post is appending rows runtime into gridview.Please follow the below code.
Default.aspx page
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td><asp:TextBox ID=”txtProductName” runat=”server”></asp:TextBox> </td>
<td><asp:TextBox ID=”txtPrice” runat=”server”></asp:TextBox> </td>
<td><asp:TextBox ID=”txtQuantity” runat=”server”></asp:TextBox> </td>
<td><asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” /></td>
</tr>
</table>
<asp:GridView ID=”gvBind” runat=”server”></asp:GridView>
</div>
</form>
</body>
</html>
Default.Cs Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dtStructure();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dtDatas"];
DataRow dr = dt.NewRow();
dr["ProductName"] = txtProductName.Text;
dr["Price"] = txtPrice.Text;
dr["Quantity"] = txtQuantity.Text;
dr["Total"] = Convert.ToInt32(txtPrice.Text) + Convert.ToInt32(txtQuantity.Text);
dt.Rows.Add(dr);
dt.AcceptChanges();
gvBind.DataSource = dt;
gvBind.DataBind();
}
public void dtStructure()
{
DataTable dt = new DataTable();
dt.Columns.Add(“ProductName”, typeof(string));
dt.Columns.Add(“Price”, typeof(Int32));
dt.Columns.Add(“Quantity”, typeof(Int32));
dt.Columns.Add(“Total”, typeof(Int32));
ViewState["dtDatas"] = dt;
}
Any doubt Comment me