Connection String 

SqlConnection con =new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);


        List<string> lst = new List<string>();
     


private void BindListBox()
        {
            DataTable dt = new DataTable();

            if (con.State != ConnectionState.Open)
                con.Open();
            using (SqlCommand cmd = new SqlCommand(@"Select Rid,Name from Tbl_Regi", con))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);

                //listbox1.DataSource = dt;
                //listbox1.DataBind();

                foreach (DataRow item in dt.Rows)
                {
                    lst.Add(item["Name"].ToString());
                }
                listbox.Items.Clear();
                listbox.DataSource = lst;
                listbox.DataBind();
            }
            if (con.State != ConnectionState.Closed)
                con.Close();
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //StringCollection sc = new StringCollection();
            List<string> lst = new List<string>();
            foreach (ListItem item in listbox1.Items)
            {
                if (item.Selected)
                {
                    lst.Add(item.Text);
                }
            }
            InsertRecords(lst);
        }
        private void InsertRecords(List<string> lst)
        {
            string qry = string.Empty;
            try
            {
                StringBuilder sb = new StringBuilder();
             
                foreach (string item in lst)
                {
                     qry = @"Insert Into Tbl_Test values";
                    sb.AppendFormat("{0}('{1}')", qry,item);
                }
                using (SqlCommand cmd = new SqlCommand(qry,con))
                {
                    cmd.CommandText = sb.ToString();
                    if (con.State != ConnectionState.Open)
                        con.Open();
                    cmd.ExecuteNonQuery();
                }
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (con.State != ConnectionState.Closed)
                    con.Close();
            }
        }

Comments

Popular posts from this blog

String Program in C#

CSV using XmlNode

Extension Method & Partial Class