我是 C#.net 的新手。我正在开发一个小型应用程序,其中一个下拉列表中的数据根据另一个下拉列表中选择的值进行填充。查看输出后,我收到错误 Invalid column name 'CategoryBasedList'
。你能指出我哪里出错了吗?我附上下面的代码。提前致谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UserLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populate();
}
}
protected void ddlCategoryBasedList_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ddlListOfBooks_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["CONN_STR"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("Select distinct(CategoryBasedList) from Category where CategoryList = '" + (ddlListOfBooks.SelectedValue).ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCategoryBasedList.DataTextField = ds.Tables[0].Columns["CategoryBasedList"].ToString();
ddlCategoryBasedList.DataSource = ds.Tables[0];
ddlCategoryBasedList.DataBind();
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
public void populate()
{
string constr = ConfigurationManager.ConnectionStrings["CONN_STR"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand(" Select distinct(CategoryList) from Category", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
ddlListOfBooks.DataTextField = ds.Tables[0].Columns["CategoryList"].ToString();
ddlListOfBooks.DataSource = ds.Tables[0];
ddlListOfBooks.DataBind();
}
}
上述表-CATEGORY的数据库结构如下。
CREATE TABLE [dbo].[Category](
[[CategoryBasedList]]] [varchar](100) NOT NULL,
[CategoryList] [varchar](100) NOT NULL,
[Authors] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
最佳答案
您需要整理 CategoryBasedList
周围的括号。正如您现在显示的那样,字段名称实际上是 [CategoryBasedList]]
,而不是您可能期望的 CategoryBasedList
。
只需重命名该列名称以删除多余的括号,您就可以开始了。
此外,如前所述,您需要注意 SQL Injections .您需要使用 SQL Parameters 而不是通过字符串连接构造查询
关于c# - 获取错误作为无效的列名称 C#.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48946014/