我得到了一個ComboBox,其中一個表格作爲數據源,ID作爲值成員和作爲顯示成員的名稱。 從ComboBox中選擇一個名稱應該用數據填充6個TextBoxes。填充文本框,數據類型對於布爾操作無效
例外:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
代碼:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = @"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (@Name, @Phone1, @Phone2, @Address, @Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("@Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("@Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("@Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("@Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("@Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("@Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("@Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
表詳細信息:
'CustomerID'是一個int,和你傳遞一個字符串。我沒有使用過SQL CE,但是你可以試試這個:'「SELECT * FROM Customers WHERE CustomerID =」+ cBox1.SelectedValue'(即,擺脫SQL查詢中的單引號)。 – Tim 2013-05-05 04:44:21
謝謝,但現在我得到了這個例外。 '解析查詢時出錯。 [令牌行號= 1,令牌行偏移量= 53,令牌出錯=數據]' – Mody 2013-05-05 04:55:20
請發佈您使用的查詢字符串。此外,在調試器中進入代碼,並在構造查詢時查看「cBox1.SelectedValue」的值。 – Tim 2013-05-05 05:21:28