bumble_bee_tuna
bumble_bee_tuna

Reputation: 3563

Programmatically Binding ComboBox(s) By Control Name

Let me preface this by saying I don't do very much winforms work so pardon my ignorance. Binding is slightly strange coming from ASP.

I'm trying loop over a series of combo boxes and bind them using a dictionary of control names and a corresponding stored procedure. Here is a simplified example of what I'm trying to do.

    public Dictionary<string, string> GetDropDownSchema()
    {
        return new Dictionary<string, string> { {"ddClient", "guisp_SelectClientDropDown"}, {"ddType", "guisp_SelectTypeDropDown"}, {"ddCounty", "guisp_SelectCountyDropDown"}};
    }

    public void BindComboBoxes()
    {
        var ddSchem = GetDropDownSchema();
        foreach (var dd in ddSchem) { 
            var dt = new DataTable();
            using (var con = new SqlConnection(ConStr)) {
                try {
                    var adapter = new SqlDataAdapter(dd.Value, con);
                    adapter.Fill(dt);

                    ((ComboBox)Controls.Find(dd.Key, true)[0]).DataSource = dt;
                    ((ComboBox)Controls.Find(dd.Key, true)[0]).DisplayMember = "DisplayText";
                    ((ComboBox)Controls.Find(dd.Key, true)[0]).ValueMember = "ID";

                }
                catch //(Exception ex)
                {
                     //Code is not throwing any exception, just doesn't work
                }

            }
        }

I'm sure I'm missing something simple with this. I appreciate any help or suggestion on a more elegant way to go about this.

Thanks

Upvotes: 0

Views: 199

Answers (1)

Steve
Steve

Reputation: 216303

I suppose that the guisp_XXXXXX are names of stored procedures. If this is the case then you cannot use them in that way to fill a datatable using a SqlDataAdapter.

Instead you need to build a SqlCommand, specify that its CommandType is StoredProcedure and assign that command to the SelectCommand property of the SqlDataAdapter

using (var con = new SqlConnection(ConStr)) 
{
    try 
    {
        con.Open();
        var adapter = new SqlDataAdapter();
        var cmd = new SqlCommand(dd.Value, con);
        cmd.CommandType = CommandType.StoredProcedure;
        adapter.SelectCommand = cmd;
        adapter.Fill(dt);
        ......

Upvotes: 1

Related Questions