我正在尝试根据前一个ComboBox的选择为ComboBox选择一组数据。我一直认为它是第二种方法中的SELECT
语句,但我无法弄清楚它为什么不起作用。当我运行应用程序时,我收到此错误:
数据类型对布尔运算无效。 [数据类型(如果 known)= int,数据类型(如果已知)= nvarchar]。
我尝试使用Parameter.AddWithValue
并将值设置为字符串无效。有人会介意教我如何正确解决这个问题吗?谢谢。
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
SqlCeConnection cn = new SqlCeConnection(@"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
答案 0 :(得分:0)
Parks表中的CityId是整数吗?
您正在比较一个int,即CityId与字符串'... cboCities.SelectedValue中的值...'
尝试将城市转换为整数:
cmd.CommandText = "SELECT Name FROM Parks WHERE CAST(CityId AS NVARCAR) ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
或者,如果您确定in cboCities.SelectedValue与CityId相同,您也可以在没有引号的情况下尝试它(整数与整数比较)
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = " + cboCities.SelectedValue + " ORDER BY Name ASC";
(注意我已删除了围绕cboCities.SelectedValue的单引号)
答案 1 :(得分:0)
您是否尝试过以下内容?
//[...code...]
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = @CityId ORDER BY Name ASC";
cmd.Parameters.Add("@CityId", System.Data.SqlDbType.Int, 2).Value = Convert.ToInt32(cboCities.SelectedValue);
//[...code...]