Combobox.SelectedItem在参数

时间:2018-10-26 13:21:19

标签: c# sql

我正在从Combobox_SelectionChanged上的表中检索数据。 每当我尝试添加参数时,它就不再获取数据。 有趣的是,如果我将值“ Combobox.SelectedItem”替换为 名称"Max",将检索数据。 另外,如果我指定“ Combobox.SelectedIndex == 1,2 or 3”,它仍然会检索数据。 Combobox.SelectedItem作为值有什么问题?

private void Combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (Combobox.SelectedIndex > -1)
        {
            string Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =";
            string dataFile = System.AppDomain.CurrentDomain.BaseDirectory;
            dataFile = "Database\\Data.accdb";

            string Selecte = "Select * FROM [Table] WHERE @1 IN([Name]) ORDER BY [Number] ASC";
            using (OleDbConnection myConnection = new OleDbConnection(Provider + dataFile))
            {

                if (myConnection.State != ConnectionState.Open)
                    myConnection.Open();

                OleDbCommand cmd = new OleDbCommand(Selecte, myConnection);

                    cmd.Parameters.Add(new OleDbParameter { ParameterName = "@1", OleDbType = OleDbType.Char, Value = Combobox.SelectedItem });
                    cmd.ExecuteNonQuery();

                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGrid.ItemsSource = dt.AsDataView();
            }
        }

1 个答案:

答案 0 :(得分:0)

cmd.Parameters.Add(new OleDbParameter { ParameterName = "@1", OleDbType = OleDbType.Char, Value = Combobox.SelectedItem });

更改为:

cmd.Parameters.Add(new OleDbParameter { ParameterName = "@1", OleDbType = OleDbType.**VarChar**, Value = Combobox.SelectedItem });