Sunday, 24 May 2015

Add (Send) TextBox Values to ListBox in ASP.Net on Button Click using C#

I will explain how to add or send textbox values to listbox in asp.net  on button click using c#,vb.net or bind textbox values to listbox on button click in asp.net 

separator


To add textbox values to listbox in asp.net  on button click using c#, vb.net we need to write aspx code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add Textbox values to Listbox items on button click </title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Text: <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add to Listbox" OnClick="btnAddClick" /> <br /> <br/>
Listbox Values:  <asp:ListBox ID="lstdetails" runat="server"></asp:ListBox>
</div>
</form>
</body>
</html>
After completion of aspx page write the add following namespaces in codebehind

C# Code


using System;
using System.Data;
VB.NET Code


Imports System.Data
After completion of adding namespaces you need to write the code like as shown below

C# Code






DataTable dt = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Details"] == null)
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Name");
ViewState["Details"] = dataTable;
}
}
}
protected void btnAddClick(object sender, EventArgs e)
{
string str = txtname.Text.Trim();
dt = (DataTable)ViewState["Details"];
dt.Rows.Add(str);
ViewState["Details"] = dt;
lstdetails.DataSource = dt;
lstdetails.DataTextField = "Name";
lstdetails.DataValueField = "Name";
lstdetails.DataBind();
txtname.Text = "";
}

No comments :

Post a Comment