我有2个下拉列表,一个用于州,一个用于城市。我正在填充数据库中的状态下拉列表,工作正常。我有一种方法,当指数改变状态时,它会填充城市下拉列表。现在出于某种原因,当我更改状态并且方法命中populateCity下拉列表时,它会给我一个错误说
我只是因为我选择了缅因州,它会在我所选择的每个州,在da.fill(ds,“City”)下发生;不确定为什么一直这样做。Sqlexception错误:列名'ME'无效
以下是州下拉列表和城市下拉列表的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand cmdState = new SqlCommand("SELECT DISTINCT state,abr FROM tbl_zip ORDER BY state ASC", con);
DataSet dsState = new DataSet();
SqlDataAdapter daState = new SqlDataAdapter(cmdState);
con.Open();
daState.Fill(dsState, "State");
States.DataSource = dsState.Tables[0];
States.DataTextField = "state";
States.DataValueField = "abr";
States.DataBind();
con.Close();
}
}
protected void States_SelectedIndexChanged(object sender, EventArgs e)
{
if (States.SelectedItem.Value != "Select")
{
string st = States.SelectedValue;
PopulateCity(st);
}
}
protected void PopulateCity(string st)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT DISTINCT city FROM tbl_zip WHERE abr = " + st, con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "City");
Cities.DataSource = ds.Tables[0];
Cities.DataTextField = "city";
Cities.DataValueField = "city";
Cities.DataBind();
}
答案 0 :(得分:2)
就像@Raphael所提到的那样,如果st
是一个字符串,那么它需要引号或者它将是无效的SQL语法,另一种方法是:
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT DISTINCT city FROM tbl_zip WHERE abr = @State";
cmd.Parameters.AddWithValue("State", st);
答案 1 :(得分:2)
状态值应该在引号内。 I-E:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT city FROM tbl_zip WHERE abr = '"+ st +"'", con);
答案 2 :(得分:1)
在PopulateCity函数中。 st需要引号。
否则它将寻找一列。
像:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT city FROM tbl_zip WHERE abr = " + "'" + st + "'", con);