Tuesday, May 8, 2012

Dynamic Fill ComboBox Winform example

public void FillCmb(ComboBox cmb, string query, string strValue, string strText, string strHeader)
{            
    con = new SqlConnection(connectionString);            
    adp = new SqlDataAdapter(query, con);
    DataTable tbl = new DataTable();
    con.Open();
    adp.Fill(tbl);       
    con.Close();
     
    DataRow header = tbl.NewRow();
    if (!string.IsNullOrEmpty(strValue))
        header[strValue] = DBNull.Value;
    header[strText] =
        (string.IsNullOrEmpty(strHeader)) ? "Choose" : strHeader;
    tbl.Rows.InsertAt(header, 0);  
          
    cmb.DataSource = tbl;            
    cmb.DisplayMember = strText;            
    cmb.ValueMember = strValue;        
}//end fill cmb

p.s.
string text = ((DataRowView)cbxSources.SelectedItem).Row[0].ToString();

No comments:

Post a Comment