Hi akhter,
If you want to insert data in gridview using datatable so you need to use viewstate.
Refer below sample.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Codeitem" HeaderText="Item" />
<asp:BoundField DataField="QTY" HeaderText="QTY" />
</Columns>
</asp:GridView>
<br />
CodeItems :
<asp:TextBox runat="server" ID="Codeitem" />
<br />
Qty :
<asp:TextBox runat="server" ID="txtqty" />
<br />
<asp:Button Text="Insert" runat="server" OnClick="GVadd_Click" />
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dt.Columns.Add("Codeitem");
dt.Columns.Add("QTY");
ViewState["dt"] = dt;
}
}
protected void GVadd_Click(object sender, EventArgs e)
{
dt = ViewState["dt"] as DataTable;
dr = dt.NewRow();
dr["Codeitem"] = Codeitem.Text;
dr["QTY"] = txtqty.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
clear();
}
private void clear()
{
Codeitem.Text = "";
txtqty.Text = "";
}
VB.Net
Private dt As DataTable = New DataTable()
Private dr As DataRow
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handle Me.Load
If Not Me.IsPostBack Then
dt.Columns.Add("Codeitem")
dt.Columns.Add("QTY")
ViewState("dt") = dt
End If
End Sub
Protected Sub GVadd_Click(ByVal sender As Object, ByVal e As EventArgs)
dt = TryCast(ViewState("dt"), DataTable)
dr = dt.NewRow()
dr("Codeitem") = Codeitem.Text
dr("QTY") = txtqty.Text
dt.Rows.Add(dr)
GridView1.DataSource = dt
GridView1.DataBind()
clear()
End Sub
Private Sub clear()
Codeitem.Text = ""
txtqty.Text = ""
End Sub
Screenshot