2015-10-15 149 views
1

我試圖弄清楚了這幾天。我有一個帶有TextBoxes(這個工作)的形式的DO/SEE/EXPECT的表單,但是當我嘗試添加一個帶有3個項目的組合框時,我總是在cmd.ExecuteNonQuery()上得到一個OleDbException。C#WPF:從組合框添加項目到訪問數據庫

類型 'System.Data.OleDb.OleDbException' 的未處理的異常出現在system.data.dll

附加信息:條件表達式中數據類型不匹配。

我在這做錯了什麼?

using System.Windows; 
using System.Data.OleDb; 
using System.Configuration; 

namespace WpfApplication3 
{ 

    public partial class Records : Window 
    { 
     public Records() 
     { 
      InitializeComponent(); 
     } 

     private void button_Click(object sender, RoutedEventArgs e) 
     { 
      OleDbConnection con = new OleDbConnection(); 
      con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ToString(); 
      con.Open(); 
      OleDbCommand cmd = new OleDbCommand(); 
      cmd.CommandText = "insert into [tblInboxRecords](DO, SEE, EXPECT, Segment) Values (@do,@see,@ex,@sg)"; 
      cmd.Parameters.AddWithValue("@do", txtdo.Text); 
      cmd.Parameters.AddWithValue("@see", txtsee.Text); 
      cmd.Parameters.AddWithValue("@ex", txtexpect.Text); 
      cmd.Parameters.AddWithValue("@sg", boxsegment.Text); // This is the combobox 
      cmd.Connection = con; 
      cmd.ExecuteNonQuery(); 
      { 
       MessageBox.Show("Item Inserted"); 
      } 

     } 

    } 
} 

這是ComboBox中的.xaml:

<ComboBox x:Name="boxsegment" HorizontalAlignment="Left" Height="20" Margin="72,85,0,0" VerticalAlignment="Top" Width="120"> 
    <ComboBoxItem Content="Type A (Operator)"/> 
    <ComboBoxItem Content="Type B (Urgent)"/> 
    <ComboBoxItem Content="Type C (Critical)"/> 
</ComboBox> 

當我在尋找解決的辦法,我只能找到如何使用的物品從你的數據庫到WPF,而不是其他辦法。

+0

什麼是你的 '段' 列的數據類型?它看起來像'string'不兼容,所以如果你想用它作爲查詢參數,你必須將'boxsegment.Text'轉換爲兼容類型。 –

+0

我假設你在討論Access中的列?我嘗試了「短文本」,「長文本」並添加了一個值列表。 – Giuliano

回答

0

找到了!

通過使用string SegmentBox = boxsegment.Text.ToString();

代替cmd.Parameters.AddWithValue("@sg", boxsegment.Text);