HOW TO SAVE MULTIPLE LISTBOX VALUE IN A SINGLE ROW AND IN A SINGLE COLUMN

jacob rasel

Total Post:88

Points:616
Posted by  jacob rasel
C# 
C#
 1417  View(s)
Ratings:
Rate this:

I want to save multiple list box value into a single field of a table using linq to entity. this is my code. any suggestion?

protected void Button5_Click(object sender, EventArgs e)
{
    for(var i = 0; i < lb2.Items.Count; i++)
    {
        var e1 = new employee() { emp_skill = lb2.Items[i].Text };
        je.employee.AddObject(e1);
    }
    je.SaveChanges();
}
  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How To Save Multiple ListBox Value in a single row and in a single column

    Hi Jacob,


    I assume your data is collection of string and you want to save it as single string. The following code make those collection of string become single string separated by semicolon, then you can save it as single row single column data:

    protected void Button5_Click(object sender, EventArgs e)
        {
            var semicolonSeparatedString = "";
            var e1 = (from emp in je.employee where emp.emp_email == txtmail.Text select emp).FirstOrDefault();
            for (int index = 0; index < lb2.Items.Count; index++)
            {
                //no need to add separator for the first item
                if (index == 0) semicolonSeparatedString += lb2.Items[index];
                else semicolonSeparatedString += ";" + lb2.Items[index];
            }
            //data formatted as single string and ready to be saved
            e1.emp_skill = semicolonSeparatedString;
            je.SaveChanges();

    And when you want to get it back as collection of string simply use Split() extension method :

    var semicolonSeparatedString = je.employee.FirstOrDefault(o => o.name == "employeeName").Select(o => o.emp_skill);
    //split to get the single string data back to array of string
    var items = semicolonSeparatedString.Split(';');
    foreach(var item in items)
    {
        lb2.Items.Add(item);
    }

      Modified On Apr-03-2018 06:35:52 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!