2013-06-17 2 views
1

Я начинаю с C#, и я встречаю некоторые проблемы.Обновить Combobox от SQL Server 2008

Red= ADD TO DB AND REFRESH

Я хотел бы знать, как обновить данные, при сохранении данных во второй форме окна (agregar_en_directorio) и хотят, чтобы отобразить новые данные в поле со списком первой формы окна (generar_tarjeta).

Conexion: conectaraBD.cs

public static SqlConnection ObtenerCOnexion() 
    { 
     SqlConnection Conn = new SqlConnection(@"Data source=MY-PC\SQLEXPRESS; Initial Catalog=myDatabase; User Id=user; Password=xxxx"); 
     Conn.Open(); 

     return Conn; 
    } 

комбо:

public void fillCombo() 
    { 
     string SQL = "select id_persona as identificador, clave_de_identificacion +' '+clave_de_la_dependencia +' '+grado_o_titulo+' '+nombre+' '+ ap+' '+ am DetallesCompletos from directorio"; 

     DataTable dt = new DataTable(); 

     using (SqlConnection Conn2 = conectaraBD.ObtenerCOnexion()) 
     { 
      using (var cmd = new SqlCommand(SQL, Conn2)) 
      { 

       try 
       { 
        dt.Load(cmd.ExecuteReader());       
       } 
       catch (SqlException e) 
       { 
        MessageBox.Show("Error al Cargar los Datos" + e.ToString(), "Error SQL", 
        MessageBoxButtons.OK, MessageBoxIcon.Error); 
       } 
      } 
     } 

     comboDe.DataSource = dt; 
     comboDe.ValueMember = "identificador"; 
     comboDe.DisplayMember = "DetallesCompletos"; 
    } 

Примечание: Используемый код для ComboBox является продолжением (используются для подобия 3 ComboBox) ,

И помогло бы мне ваше мнение о GUI

+0

Unl ike форумах, мы не используем «Спасибо», или «Любая помощь оценена», или подписи на [so]. См. «[Должны ли« Привет »,« спасибо », теги и приветствия удалены из сообщений?] (Http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed-from-posts). –

ответ

1

я решил, но мне пришлось изменить некоторые вещи:

public static DataTable dataFortheCombos() 
    { 
     DataTable dt = new DataTable(); 

     SqlConnection connection = new SqlConnection(@"Data source=SAMANIEGO-PC\SQLEXPRESS; Initial Catalog=banco_de_datos; User Id=user; Password=xxx");/ 

     string query = "select id_person as identifier, identification_key +' '+dependence_key +' '+degree_or_title+' '+name+' '+ ap+' '+ am as completedetails from directory"; 
     SqlCommand cmd = new SqlCommand(query, connection); 

     SqlDataAdapter adap = new SqlDataAdapter(cmd); 

     adap.Fill(dt); 
     return dt; 
    } 

    public static AutoCompleteStringCollection autocompleteCombos() 
    { 
     DataTable dt = dataFortheCombos(); 

     AutoCompleteStringCollection coleccion = new AutoCompleteStringCollection();   
     foreach (DataRow row in dt.Rows) 
     { 
      coleccion.Add(Convert.ToString(row["completedetails"])); 
     } 

     return coleccion; 
    } 

    public void fillCombos() 
    {         
     comboFrom.DataSource = dataFortheCombos(); 
     comboFrom.DisplayMember = "completedetails"; //This is the value shown on the combo for the user 
     comboFrom.ValueMember = "identifier"; // The selectedc value insert as identifier (is a number) 
     comboFrom.SelectedIndex = -1; //Clear the combo    

     //NOTE -> The others combos (urned over and sender) using the same data 

    } 

Событие --onfocus-- используется для вызовите обновление, когда пользователь находится в combobox comboFrom

 private void comboDe_Enter(object sender, EventArgs e) 
      { 
       comboFrom.DataSource = null //Clear the Combo Box 
       //NOTE -> The others combos (urned over and sender) using the same data 
       fillCombos();     
      } 
+0

FYI, ваши 'SqlConnection',' SqlCommand' и 'SqlDataAdapter' все должны быть в' использовании'. –

+0

Большое спасибо за ваш комментарий, учтите это, и я Я все еще улучшаю код. – samaniego