使用组合框将列表视图与SQL表组合起来
本文关键字:组合 SQL 视图 起来 列表 | 更新日期: 2023-09-27 18:29:58
我正试图获得一个组合框来在列表视图中填充技术的发票,但到目前为止还不起作用。
这是我在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();
}
您的比较似乎不正确。
combox.text设置为Tech.First + ' ' + Tech.Last
,但当您检查comboBox1_SelectedIndexChanged()时,会将其与Tech.Last
进行比较。将其更改为WHERE First + ' ' + Last='" + comboBox1.Text + "'
。因此,总之,您将组合框项目设置为"John Doe",然后在发票列表视图中填充Tech.Last为"John Do"的记录。