C# 从下拉列表中插入多行到SQL

C# 从下拉列表中插入多行到SQL,c#,sql,foreach,sql-insert,C#,Sql,Foreach,Sql Insert,我有6个DropDownList,具有以下值 ABC,DEF,GHI,JKL,MNO,PQR 我想通过从每个dropdownlist中获取值,将ddl1、ddl2、ddl3、ddl4、ddl5和ddl6中的值插入到我的SQL表中 我目前有以下内容,但需要对其进行调整,以插入每个dropdownlist中的值,而不是相同的值: SqlConnection sqlCon = new SqlConnection("Data Source=***; User ID=***; MultipleActiv

我有6个DropDownList,具有以下值

ABC,DEF,GHI,JKL,MNO,PQR
我想通过从每个dropdownlist中获取值,将ddl1、ddl2、ddl3、ddl4、ddl5和ddl6中的值插入到我的SQL表中

我目前有以下内容,但需要对其进行调整,以插入每个dropdownlist中的值,而不是相同的值:

SqlConnection sqlCon = new SqlConnection("Data Source=***; User ID=***; MultipleActiveResultSets=True; Password=***; Initial Catalog=PMRDA;");

try
{
    sqlCon.Open();

    foreach (string str in AllOptions)
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO lboard(eventType, date, college) values (@eventType, GETDATE(), @college)", sqlCon);

        SqlParameter eventType = cmd.Parameters.Add("@eventType", SqlDbType.VarChar);
        SqlParameter college = cmd.Parameters.Add("@college", SqlDbType.Char);

        eventType.Value = ddlEventType.SelectedItem.Value;
        college.Value = ddl5.SelectedItem.Value;

        cmd.ExecuteNonQuery();
    }

    LabelStatus.Text = "Submitted Succesfully";
}
catch(Exception ex)
{
    LabelStatus.Text = ex.Message;
}
finally
{
    sqlCon.Close();
}

在foreach循环中,有一个allOptions字符串列表 (我假设这是一个包含ddl中所有SelectedValue的列表)

换衣服

college.Value = ddl5.SelectedItem.Value;

否则的话,你会有一个foreach循环和一个你从未使用过的对象

评论后编辑

创建一个包含2个字符串属性的类 StringSome=您要拥有的字符串,stringDrop=下拉列表selectedvalue

public class MyClass
{
 public string StringSome{get;set;}
 public stirng StringDrop{get;set;}
 public MyClass()
 {//default constructor}
 public MyClass(string a, string b)
 {
  StringSome = a; 
  StringDrop = b;}
 }
改变

Alloptions = new List<string>();
college.Value = str;
将foreach循环保持在AllOptions上

改变

Alloptions = new List<string>();
college.Value = str;


使用str.StringSome作为其他参数

在下拉列表中迭代,如果该列表是
list1

  foreach (string str in list1)
{    
....
college.Value = str;
....
}

但是,这样做并没有任何意义,在
下拉列表框
(这样选择就失去了它的使用点),您可以简单地将它们存储在一个简单的
列表

中,只需为每个组合框添加这样的for语句即可。

string text_to_add;
for (int i=0; i< comboBox.Items.Count; i++)
{
    text_to_add=comboBox.Items[i].ToString();
    //Perform the db insert using the text_to_add string
}
要添加的字符串文本;
对于(int i=0;i
下拉列表指的是组合框,对吗?谢谢@Schuere-你说得对,STR中确实包含选定的值,我如何同时输入另一个选定值的字符串数组?
  foreach (string str in list1)
{    
....
college.Value = str;
....
}
string text_to_add;
for (int i=0; i< comboBox.Items.Count; i++)
{
    text_to_add=comboBox.Items[i].ToString();
    //Perform the db insert using the text_to_add string
}