简体   繁体   中英

ComboBox SelectedItem from DataTable Winforms C#?

I have a method in my DAL which populates a ComboBox from a DataTable . ComboBox displays correctly and I have a 'Save' button which saves back to my DB, job's a good'un...

 public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
    {
        SqlCommand _comm = new SqlCommand();
        _comm.Parameters.AddWithValue("@id", Id);
        _comm.CommandText = "SELECT [name] FROM dbo.fnGetName(@id) ORDER BY [name]; ";   
        _comm.Connection = _conn;
        _comm.CommandTimeout = _command_timeout;

        DataTable dt = new DataTable();
        try
        {
            SqlDataReader myReader = _comm.ExecuteReader();
            dt.Load(myReader);
        }
        catch
        {
            MessageBox.Show("Unable to populate Name LookUp");
        }

        Combo.DataSource = dt;            
        Combo.DisplayMember = "name";

        foreach (DataRow dr in dt.Rows)
        {
            if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
            {
                Combo.SelectedItem = dr["company_int_name"].ToString();
            }
        }
        return "";
    }

However obviously when I re-edit the record, this method is called again. Ok, I now have written a ForEach loop which iterates over my DataTable and compares the string in the rows to the Name I am passing in. If the two match I'm setting the

Combo.SeletedItem =  dr["company_int_name"].ToString();

However the selectedItem is not being set, presumably I'll need some sort of event to notify the property changed?

Thanks

You have to bind the Combo Box with the ValueMember function and can reflect the combo box with the matched string value as selected

public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
    SqlCommand _comm = new SqlCommand();
    _comm.Parameters.AddWithValue("@id", Id);
    _comm.CommandText = "SELECT [name] FROM dbo.fnGetName(@id) ORDER BY [name]; ";   
    _comm.Connection = _conn;
    _comm.CommandTimeout = _command_timeout;

    DataTable dt = new DataTable();
    try
    {
        SqlDataReader myReader = _comm.ExecuteReader();
        dt.Load(myReader);
    }
    catch
    {
        MessageBox.Show("Unable to populate Name LookUp");
    }

    Combo.DataSource = dt;            
    Combo.DisplayMember = "name";
    Combo.ValueMember = "name";

    foreach (DataRow dr in dt.Rows)
    {
        if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
        {
            Combo.SelectedValue = dr["company_int_name"].ToString();
        }
    }
    return "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM