2012-11-09 2 views
0

내 목록의 선택된 항목을 내보내려고 시도했는데 목록의 특정 항목이 어디에 있는지 알 수 있지만 텍스트를 가져올 수 없습니다. 해당 항목 위치에서 변수로.선택한 항목을 SQL 데이터베이스로 내보내기

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 = [email protected] 
      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(); 
    }   
} 

답변

3

이 시도 :

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(); 
       } 
      } 
     }  
    } 
} 
+0

당신은 나의 영웅 선생님이다가, 친절 감사합니다. – sgl

관련 문제