문제

MSSQL View (Vcustomer)에서 고객 정보를 검색하고 반환하는 데 사용되는 양식에 텍스트 상자, 콤보 상자, 버튼 및 DatagridView가 있습니다. 잘 작동하지만 내 코드가 더 효율적 일 수 있다는 것을 알고 있습니다. Combobox의 4 가지 항목은 검색 할 열을 나타냅니다.

다음을 동적 LINQ로 SQL로 변환하는 간단한 방법이 있습니까? 나는 C#을 처음 접했다. 다른 게시물을 확인했지만 작동하지 않는 것 같습니다.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        // columns to filter for
        string[] list = new string[4];
        list[0] = "Name";
        list[1] = "CustomerAccountNo";
        list[2] = "Telephone";
        list[3] = "Postal";

        // bind to combobox
        cboColumn.DataSource = list;
        cboColumn.SelectedIndex = 0;
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {

        try
        {
            Cursor.Current = Cursors.WaitCursor; 
            CustomerSearchDataContext db = new CustomerSearchDataContext();
            IEnumerable<vCustomer> customerQuery = null;
            switch (cboColumn.SelectedIndex)
            {
                case 0:
                    customerQuery = from c in db.vCustomers
                                    where c.Name.Contains(txtSearch.Text)
                                    orderby c.CustomerAccountNo descending
                                    select c;
                    break;
                case 1:
                    customerQuery = from c in db.vCustomers
                                    where c.Name.Contains(txtSearch.Text)
                                    orderby c.CustomerAccountNo descending
                                    select c;
                    break;
                case 2:
                    customerQuery = from c in db.vCustomers
                                    where c.Telephone.Contains(txtSearch.Text)
                                    orderby c.CustomerAccountNo descending
                                    select c;
                    break;
                case 3:
                    customerQuery = from c in db.vCustomers
                                    where c.Postal.Contains(txtSearch.Text)
                                    orderby c.CustomerAccountNo descending
                                    select c;
                    break;
            }
            customerBindingSource.DataSource = customerQuery;
            dataGridView1.DataSource = customerBindingSource;
            dataGridView1.Columns["CustomerId"].Visible = false;
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            MessageBox.Show("An Error Occured - " + ex.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            Cursor.Current = Cursors.Default; 
        }
    }
}
도움이 되었습니까?

해결책

사용 [System.Linq.Dynamic][1].

메소드에서 조건을 가져 와서 단일 쿼리에서 사용하십시오.

    switch (choice)
    {
        case case1:
            condition = string.Format("{0}.Contains({1})", "Column", "Value"
            break;

다른 팁

이봐 로니. 나는 당신의 제안을 시도하고 내 코드를 다시 고려했습니다 (아래 참조). 그러나 오류가 발생합니다. 'Smith'는 'Vcustomer'유형에 존재하지 않습니다. . 그건 그렇고, messagebox.show (조건); 라인 반환 name.contains (Smith) 올바른 것처럼 보입니다.

내가 뭘 잘못하고 있죠? 멍청이가되어 죄송합니다. 도와 주셔서 감사합니다.

알아 냈습니다 ... 검색 문자열을 이중 인용문으로 랩핑해야했습니다! 코드가 편집되었습니다.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }
    private void MainForm_Load(object sender, EventArgs e)
    {
        // data column to filter against
        string[] list = new string[4];
        list[0] = "Name";
        list[1] = "CustomerAccountNo";
        list[2] = "Telephone";
        list[3] = "Postal";
        cboColumn.DataSource = list;
        cboColumn.SelectedIndex = 0;

        // left, right or middle search
        string[] list2 = new string[3];
        list2[0] = "Contains";
        list2[1] = "StartsWith";
        list2[2] = "EndsWith";
        cboFilterAtt.DataSource = list2;
        cboFilterAtt.SelectedIndex = 0;
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            Cursor.Current = Cursors.WaitCursor; 
            CustomerSearchDataContext db = new CustomerSearchDataContext();
            //string condition = string.Format("{0}.{1}({2})", cboColumn.SelectedValue, cboFilterAtt.SelectedValue, txtSearch.Text);
            string condition = string.Format("{0}.{1}({2})", cboColumn.SelectedValue, cboFilterAtt.SelectedValue, "\"" + txtSearch.Text + "\"");
            MessageBox.Show(condition);
            var customerQuery = db.vCustomers.Where(condition).OrderBy("CustomerAccountNo");
            customerBindingSource.DataSource = customerQuery;
            dataGridView1.DataSource = customerBindingSource;
            dataGridView1.Columns["CustomerId"].Visible = false;
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            MessageBox.Show("An Error Occured - " + ex.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            Cursor.Current = Cursors.Default; 
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top