我得到了一个 ComboBox,其中表作为数据源,ID 作为值成员,名称作为显示成员。从 ComboBox 中选择一个名称应使用数据填充 6 个文本框。
例外:
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();
}
}
表详细信息: