Home > DeveloperSection > Forums > How To Save Multiple ListBox Value in a single row and in a single column
jacob rasel
jacob rasel

Total Post:88

Points:616
Posted on    December-16-2013 12:38 AM

 C# C# 
Ratings:


 1 Reply(s)
 830  View(s)
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();

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    December-16-2013 12:54 AM

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);

}


Don't want to miss updates? Please click the below button!

Follow MindStick