使用Combobox用SQL表填充listview

时间:2014-11-10 18:12:28

标签: c# sql-server listview combobox

我试图让一个组合框填充列表视图中的技术发票,但到目前为止它还没有工作。

这是我在SQL server中的表:

Tech

Tech_Id (PK) | First | Last | Phone | Customer_Count | --------------+-------+------+-------+----------------+ 1 | Tim | Bo |9384027| 7 | 2 | Andy | Wong |9374927| 8 | 3 | Jack | Help |2183847| 8 |

Invoices

Invoice_Id (PK) | Job_Descr |Job_Date | Total | Term | Customer_Id | Tech_Id | -----------------+-------------+---------+-------+------+-------------+---------+ 1 |Changed Motor|11/3/2014| $30 | 30 | 2 | 1 | 2 |Tune up |4/15/2013| $50 | 30 | 11 | 2 | 3 |Changed PS |9/14/2014| $100 | 30 | 8 | 1 |

这是我在c#中的代码:

    public TechForm()
    {
        InitializeComponent();

        SqlDataAdapter da = new SqlDataAdapter("SELECT (First+' '+Last) AS Name FROM Tech Order By First", con);
        con.Open();

        DataTable dt = new DataTable();

        da.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            comboBox1.Items.Add(dt.Rows[i]["Name"]);
        }

        con.Close();

    }


    private void button1_Click(object sender, EventArgs e)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO Tech (First, Last, Phone) VALUES ('" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        con.Open();
        SqlCommand cm = new SqlCommand("SELECT * FROM Invoices JOIN Tech ON Invoices.Tech_Id = Tech.Tech_Id WHERE Last='" + comboBox1.Text + "' ; ", con);


            try
            {
                SqlDataReader dr = cm.ExecuteReader();

                while (dr.Read())
                {
                    ListViewItem item = new ListViewItem(dr["Invoice_Id"].ToString());
                    item.SubItems.Add(dr["Job_Descr"].ToString());
                    item.SubItems.Add(dr["Job_Date"].ToString());
                    item.SubItems.Add(dr["Total"].ToString());
                    item.SubItems.Add(dr["Customer_Id"].ToString());

                    listView1.Items.Add(item);

                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            con.Close();
    }

1 个答案:

答案 0 :(得分:0)

您似乎正在进行不正确的比较。

combobox.text设置为Tech.First + ' ' + Tech.Last,但当您检查comboBox1_SelectedIndexChanged()时,将其与Tech.Last进行比较。将其更改为WHERE First + ' ' + Last='" + comboBox1.Text + "'。因此,总而言之,您将组合框项目设置为&#39; John Doe&#39;,然后在发票列表视图中填写Tech.Last是John Doe&#39;。

的记录。