在WPF中使用数据表填充ComboBox

时间:2017-07-03 13:03:04

标签: c# .net wpf

我正在创建一个允许用户在所选SQL数据库中插入各种记录的应用程序。我想知道的是使用从SQL表中提取的必需项来填充ComboBox的最有效方法。

以下是我的应用程序的当前代码段。

我的方法类的代码段:

public DataSet PullItems(string column, string db)
{
    using (SqlConnection SqlCon = new SqlConnection(db))
    {
        using (DataSet dt = new DataSet())
        {
            //Check sql connection state
            if (!(SqlCon.State == System.Data.ConnectionState.Open))
            {
                SqlCon.Open();
            }

            try
            {
                //define stored commands and populate adapter
                using (SqlCommand com = new SqlCommand("PullComboBoxItem", SqlCon))
                {
                    //define sql command types, timeout, and add procedure values
                    com.CommandType = CommandType.StoredProcedure;
                    com.CommandTimeout = 3;
                    com.Parameters.AddWithValue("@column", column);

                    //fill data adapter and return
                    SqlDataAdapter adap = new SqlDataAdapter(com);

                    adap.Fill(dt);
                    return dt;
                }
            }
            catch
            {
                //Error message to be impleme
                return null;
            }
        }
    }
}

我的WPF窗口类的代码片段:

private void getItems(string id)
{
    if (CypherDef.CheckEnvironment(CypherDef.envir))
    {
         txt_deliverymethod.ItemsSource = CypherClass.PullItems(id, CypherDef.eprocurementDBConnection).Tables;
    }
    else
    {
        MessageBox.Show("Connection Lost to Database");
    }
}
来自GUI的

XAML代码片段:

<ComboBox x:Name="txt_deliverymethod" DisplayMemberPath="DeliveryMethod" Width="150" Margin="20,5,0,0" Height="25" BorderThickness="1,1,1,2" SelectedIndex="0">
    <!--TODO:Delivery Method and auto fill combo box items on form load-->
</ComboBox>

请原谅我的草率代码,因为我很新,但我欢迎提示和建设性的批评。如果你认为我的问题很模糊,我很乐意详细说明。

1 个答案:

答案 0 :(得分:0)

错误在我的存储过程中。请参阅下面的错误和我的存储过程的解决方案。

以下是我的错误:

SELECT @column FROM [TABLE]

以下是我的修复:

SET @STRSQL = 'SELECT DISTINCT ' + @column + ' FROM [Table]'
EXECUTE SP_ExecuteSQL @STRSQL

再次感谢您的帮助。

相关问题