简体   繁体   English

'='附近的语法不正确。 [WindowsForm]

[英]Incorrect Syntax Near '='. [WindowsForm]

I am trying to load data to ComboBox from SQL Server. 我正在尝试从SQL Server将数据加载到ComboBox。

This is the method where the error occurs. 这是发生错误的方法。

While debugged, this exception is caught after the following line: 在调试时,此异常在以下行之后捕获:

metroComboBoxFilterResultsCustomer.ValueMember = "[CD_Id]";

Not sure what went wrong. 不知道出了什么问题。 Please let me know the solution for this issue. 请让我知道此问题的解决方案。

try
{
    string cDateFrom = DateTime.Parse(metroDateTimeCFrom.Text).ToString("yyyy-MM-dd");
    string cDateTo = DateTime.Parse(metroDateTimeCTo.Text).ToString("yyyy-MM-dd");
    dbconnection.Open();
    DataTable dtName = new DataTable();
    string query = "SELECT CD_Id, CD_Customer_Name, CD_Effective_From, CD_Is_Active FROM ADM_Customer_Details WHERE CD_Is_Active = 1 AND CD_Effective_From BETWEEN @cDateFrom AND @cDateTo";
    SqlCommand com = new SqlCommand(query, dbconnection);
    com.Parameters.Add("@cDateFrom", SqlDbType.DateTime).Value = cDateFrom;
    com.Parameters.Add("@cDateTo", SqlDbType.DateTime).Value = cDateTo;
    SqlDataReader reader = com.ExecuteReader();
    if (reader.Read())
    {
        dtName.Load(reader);
    }
    var listNames = CustomerName.ConvertDataTableToList<CustomerIdNameHolder>(dtName)
                 .Where(x => x.CD_Customer_Name == metroTextBoxFilterCName.Text).ToList();
    metroComboBoxFilterResultsCustomer.DisplayMember = "[CD_Customer_Name]";
    metroComboBoxFilterResultsCustomer.ValueMember = "[CD_Id]";
    metroComboBoxFilterResultsCustomer.DataSource = listNames;
}
catch (SqlException ex)
{
    throw ex;
}
finally
{
    if (dbconnection.State == ConnectionState.Open)
        dbconnection.Close();
}

FOR YOUR REFERENCE 供你参考

Please have a reference of the following class files which involves with this code. 请参考与该代码有关的以下类文件。

Class File: CustomerName.cs 类文件:CustomerName.cs

public static class CustomerName
{
    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)   
        {
            if (property.PropertyType == typeof(System.DayOfWeek))
            {
                DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                property.SetValue(item, day, null);
            }
            else
            {
                property.SetValue(item, row[property.Name], null);
            }
        }
        return item;
    }
    public static List<T> ConvertDataTableToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        List<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }
        return result;
        //var customerName = dt.AsEnumerable().Select(dataRow => new CustomerName { Name = dataRow.Field<string>("SUQ_Question") }).ToList();
    }

}

Class File: CustomerIdNameHolder 类文件:CustomerIdNameHolder

class CustomerIdNameHolder
{
    public int CD_Id
    {
        get; set;
    }

    public string CD_Customer_Name
    {
        get; set;
    }
}

Project File Download 项目文件下载

If you consider for more details, please download the partial project source code here . 如果您考虑更多详细信息,请在此处下载部分项目源代码。

Please check in your system. 请检查您的系统。 I have enclosed both application(debugged)and SQL Scripts so that you encounter the same issue I have. 我同时附上了应用程序(已调试)和SQL脚本,以便您遇到与我相同的问题。

Please let me know if anyone fixes this issue. 请让我知道是否有人解决此问题。

Many Thanks. 非常感谢。

You have multiple issues: 您有多个问题:

You should not use "[" and "]" when specifying property names for comboBox's Display and value members. 为comboBox的Display和value成员指定属性名称时,请勿使用“ [”和“]”。

You may not use Readed.Read before loading the data into the DataTable. 在将数据加载到数据表之前,您可能不使用Readed.Read。

    DateTime cDateFrom = DateTime.Parse(metroDateTimeCFrom.Text);
    DateTime cDateTo = DateTime.Parse(metroDateTimeCTo.Text);
    dbconnection.Open();
    DataTable dtName = new DataTable();
    string query = "SELECT CD_Id, CD_Customer_Name, CD_Effective_From, CD_Is_Active 
                    FROM ADM_Customer_Details WHERE CD_Is_Active = 1 AND CD_Effective_From 
                    BETWEEN @cDateFrom AND @cDateTo";
    SqlCommand com = new SqlCommand(query, dbconnection);
    com.Parameters.Add("@cDateFrom", SqlDbType.DateTime).Value = cDateFrom;
    com.Parameters.Add("@cDateTo", SqlDbType.DateTime).Value = cDateTo;
    SqlDataReader reader = com.ExecuteReader();
    dtName.Load(reader);
    var listNames = CustomerName.ConvertDataTableToList<CustomerIdNameHolder>(dtName)
                 .Where(x => x.CD_Customer_Name == metroTextBoxFilterCName.Text).ToList();
    metroComboBoxFilterResultsCustomer.DisplayMember = "CD_Customer_Name";
    metroComboBoxFilterResultsCustomer.ValueMember = "CD_Id";
    metroComboBoxFilterResultsCustomer.DataSource = listNames;

The problem is not in the code shown but in the event handler 问题不在显示的代码中,而在事件处理程序中

metroComboBoxFilterResultsCustomer_SelectedValueChanged

this event handler is called after you set the ValueMember or DisplayMember property in the code above. 在上面的代码中设置ValueMember或DisplayMember属性后,将调用此事件处理程序。 The first thing that code does is to try to select 代码要做的第一件事是尝试选择

string query = @"SELECT * FROM ADM_Customer_Details 
                WHERE CD_Is_Active=1 AND CD_Id = " + 
               metroComboBoxFilterResultsCustomer.SelectedValue;

But at this point the SelectedValue of the metroComboBoxFilterResultsCustomer is null and this produces an incorrect sql string: 但是在这一点上,metroComboBoxFilterResultsCustomer的SelectedValue为null,这会产生错误的sql字符串:

"SELECT * FROM ADM_Customer_Details WHERE CD_Is_Active=1 AND CD_Id = "

And correctly this is the cause of the Incorrect Syntax Near "=" (You can try this putting a breakpoint in that event handler to see the order of code events) 正确地,这是不正确的语法在“ =”附近的原因(您可以尝试在此事件处理程序中放置一个断点以查看代码事件的顺序)

Just fix that code adding a test for null 只需修复该代码即可添加null测试

private void metroComboBoxFilterResultsCustomer_SelectedValueChanged(object sender, EventArgs e)
{
    try
    {
        if (metroComboBoxFilterResultsCustomer.SelectedValue == null)
            return;
        ....

SIDE NOTE: Having looked at your code I really suggest you to remove that global connection with all the checks for open/close. 旁注:查看代码后,我真的建议您通过所有打开/关闭检查来删除该全局连接。 The connection is a disposable object which contains Unmanaged Resources that should be kept for the minimum amount of time possible. 连接是一个一次性对象,其中包含非托管资源 ,应将其保留在尽可能短的时间内。
The coding pattern here is CREATE/OPEN/USE/CLOSE/DISPOSE and this is the scenario in which the using statement around a disposable object is mandatory 此处的编码模式是CREATE / OPEN / USE / CLOSE / DISPOSE,在这种情况下,必须围绕一次性对象使用using语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM