简体   繁体   中英

Incorrect Syntax Near '='. [WindowsForm]

I am trying to load data to ComboBox from SQL Server.

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

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

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.

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.

You may not use Readed.Read before loading the data into the DataTable.

    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. 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:

"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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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