如何将列表框中的多个项目存储到数据库中 [英] how to store multiple item from listbox into database

查看:72
本文介绍了如何将列表框中的多个项目存储到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我真的坚持了4小时.这是我的代码:列表框上有职员姓名

hi guys,

i really stuck on this for 4hours.this is my code:listbox that has name of staff

foreach (ListItem item in ListBox1.Items)
{

    if (item.Selected)
    {

                com2.Parameters["@ListBox1"].Value += item.Text + ",";
     }
            //else
                //com2.Parameters["@ListBox1"].Value += item.Text + " ";
}


我希望它存储是否item.selected多于1个项目,然后用逗号存储.如果仅选择了1个项目则没有逗号.目前我的数据显示逗号,即使我选择了1个项目.如果2个项目(例如:michael,daniel,),我也不需要名称后面的逗号(例如:michael,daniel).


i want it store if item.selected more than 1 item then store with comma.else if only 1 item had selected then no comma. currently my data display comma even i select 1 item.i dont need the comma after name (eg: michael,) if 2 items (eg:michael,daniel,) i dont want like this

推荐答案

Boolean IsFirst=True;
foreach (ListItem item in ListBox1.Items)
{
 
    if (item.Selected)
    {
            if (IsFirst)
              {
                com2.Parameters["@ListBox1"].Value = item.Text;
                IsFirst=False;
              }
            else
              {
                com2.Parameters["@ListBox1"].Value +=","+ item.Text;
              }
     }
}


希望这是您的完美解决方案


Hopefully It is your perfect solution


string strSelected = string.Empty;
foreach (ListItem item in ListBox1.Items)
{
    if (item.Selected)
    {
           if(strselected == string.empty)
              strselected = item.text
           else
              strSelected += "," + item.Text 
    }
   
}




请使用以下代码来修饰逗号:
Hi,

Please use following code for trimming comma:
string strSelected = string.Empty;
foreach (ListItem item in ListBox1.Items)
{ 
    if (item.Selected)
    { 
        strSelected += item.Text + ",";
    }
    strSelected = strSelected.TrimEnd(',');
    
}
com2.Parameters["@ListBox1"].Value = strSelected;


这篇关于如何将列表框中的多个项目存储到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆