C# 将所选项目导出到SQL数据库
在我尝试导出列表中的选定项时,我已经知道某个项在列表中的顺序,但无法将该项位置的文本转换为变量C# 将所选项目导出到SQL数据库,c#,sql-server,C#,Sql Server,在我尝试导出列表中的选定项时,我已经知道某个项在列表中的顺序,但无法将该项位置的文本转换为变量 if (CustomerListbox.SelectedIndex > -1) { for (int i = 0; i < CustomerListbox.GetSelectedIndices().Count(); i++) { SqlConnection sqlConn = Connection.GetConnection(); SqlCo
if (CustomerListbox.SelectedIndex > -1)
{
for (int i = 0; i < CustomerListbox.GetSelectedIndices().Count(); i++)
{
SqlConnection sqlConn = Connection.GetConnection();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlConn;
{
ListItem li = new ListItem();
li.Value = Convert.ToString(CustomerListbox.GetSelectedIndices().GetValue(i)); //Determines position within listbox
li.Text = Convert.ToString(CustomerListbox.Items.FindByValue(li.Value));
//^^^some magic line of code to do li.text = Items.somethingselected@position5.Value
sqlCmd.CommandText = "ExportCustomers";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("myquery", "insert into CustomerSelect(Customers) values('" + li.Text + "')");
}
try
{
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
}
catch (Exception e2)
{
throw e2;
}
sqlConn.Close();
}
}
if(CustomerListbox.SelectedIndex>-1)
{
对于(int i=0;i
试试这个:
if (CustomerListbox.SelectedIndex > -1)
{
foreach(ListItem litem in CustomerListbox.Items)
{
if (litem.Selected == True)
{
using(SqlConnection sqlConn = Connection.GetConnection())
{
using(SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
ListItem li = new ListItem();
li.Value = litem.Value; //Determines position within listbox
li.Text = litem.Text;
sqlCmd.CommandText = "ExportCustomers";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("myquery", "insert into CustomerSelect(Customers) values('" + li.Text + "')");
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
}
}
}
}
}
试试这个:
if (CustomerListbox.SelectedIndex > -1)
{
foreach(ListItem litem in CustomerListbox.Items)
{
if (litem.Selected == True)
{
using(SqlConnection sqlConn = Connection.GetConnection())
{
using(SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
ListItem li = new ListItem();
li.Value = litem.Value; //Determines position within listbox
li.Text = litem.Text;
sqlCmd.CommandText = "ExportCustomers";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("myquery", "insert into CustomerSelect(Customers) values('" + li.Text + "')");
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
}
}
}
}
}