Pass (Send) TextBox value to ASP.Net GridView using C# and VB.Net

Last Reply 7 months ago By dharmendr

Posted 7 months ago

How to pass asp.net textbox to Gridview in asp.net?

I want to add the textbox values to gridview in asp.net

You are viewing reply posted by: dharmendr 7 months ago.
Posted 7 months ago

Hi SUJAYS,

Check this example. Now please take its reference and correct your code.

You can use Session or ViewState to keep the record.

HTML

<asp:TextBox runat="server" ID="txtValue" OnTextChanged="TextChanged" AutoPostBack="true" /><br /><br />
<asp:GridView runat="server" ID="gvDetails" EmptyDataText="No record found." />

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridView();
    }
}

private void BindGridView()
{
    gvDetails.DataSource = ViewState["Data"] as System.Data.DataTable;
    gvDetails.DataBind();
}

protected void TextChanged(object sender, EventArgs e)
{
    System.Data.DataTable dt;
    if (ViewState["Data"] == null)
    {
        dt = new System.Data.DataTable();
        dt.Columns.Add("Name");
    }
    else
    {
        dt = ViewState["Data"] as System.Data.DataTable;
    }
    dt.Rows.Add((sender as TextBox).Text.Trim());
    dt.AcceptChanges();
    ViewState["Data"] = dt;

    BindGridView();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindGridView()
    End If
End Sub

Private Sub BindGridView()
    gvDetails.DataSource = TryCast(ViewState("Data"), Data.DataTable)
    gvDetails.DataBind()
End Sub

Protected Sub TextChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As Data.DataTable
    If ViewState("Data") Is Nothing Then
        dt = New Data.DataTable()
        dt.Columns.Add("Name")
    Else
        dt = TryCast(ViewState("Data"), Data.DataTable)
    End If
    dt.Rows.Add((TryCast(sender, TextBox)).Text.Trim())
    dt.AcceptChanges()
    ViewState("Data") = dt
    BindGridView()
End Sub

Screenshot