Add and reload new items in the listbox

Satyapriyanayak
Posted by Satyapriyanayak under C# category on | Points: 40 | Views : 1268
We will know how to insert records to database and show one column of inserted items into a listbox.Here we use two textboxes, button and a listbox.And after adding items it is automatically loaded to the listbox.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace After_add_new_item_reload_listbox
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"server = HOME-SAT/SQLEXPRESS;data source = .; initial catalog = test; user id=sa;pwd =pintu ;integrated security = SSPI");
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
string str;
DataTable dt;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
listboxbind();
}

private void listboxbind()
{
con.Open();
str = "select * from employee";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "employee");
dt = ds.Tables["employee"];
listBox1.DisplayMember = "empid";
listBox1.ValueMember = "empname";
listBox1.DataSource = ds.Tables["employee"];
con.Close();
}

private void btn_add_Click(object sender, EventArgs e)
{
com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "insert into employee values(@empid,@empname)";
com.Parameters.Clear();
com.Parameters.AddWithValue("@empid", txt_id.Text);
com.Parameters.AddWithValue("@empname", txt_name.Text);
if (con.State == ConnectionState.Closed)
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data entered successfully!!!");
listboxbind();
clear();
}

private void clear()
{
txt_id.Text = "";
txt_name.Text="";
}
}
}

Comments or Responses

Login to post response