我如何从2个不同的表中填充2个组合框?

时间:2016-02-10 09:14:26

标签: c# sql ado.net

我需要从2个不同的表中填充2个组合框。这种方式不起作用。

private void client_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "Data Source=.;Initial Catalog=SCP_DB;Integrated Security=True";
    con.Open();
    string query = "select  Operation_Type from Operations_Types";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "Operations_Types");
    comboOpType.DisplayMember = "Operation_Type";
    comboOpType.ValueMember = "Operation_Type";
    comboOpType.DataSource = ds.Tables["Operations_Types"];

    da.Fill(ds, "Payment_Type");
    comboPayType.DisplayMember = "Payment_Types";
    comboPayType.ValueMember = "Payment_Types";
    comboPayType.DataSource = ds.Tables["Payment_Type"];
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.ExecuteNonQuery();
    con.Close();
}

1 个答案:

答案 0 :(得分:1)

您应该调用sql实例中的每个表,并使用TableMappings

像这样更改您的代码。

private void client_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "Data Source=.;Initial Catalog=SCP_DB;Integrated Security=True";
    con.Open();
    string query = "select  Operation_Type from Operations_Types; select ? from Payment_Type";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    da.TableMappings.Add("Table", "Operations_Types");
    da.TableMappings.Add("Table1", "Payment_Type");
    DataSet ds = new DataSet();
    da.Fill(ds, "Table");
    comboOpType.DisplayMember = "Operation_Type";
    comboOpType.ValueMember = "Operation_Type";
    comboOpType.DataSource = ds.Tables["Operations_Types"];

    da.Fill(ds, "Table1");
    comboPayType.DisplayMember = "Payment_Types";
    comboPayType.ValueMember = "Payment_Types";
    comboPayType.DataSource = ds.Tables["Payment_Type"];
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.ExecuteNonQuery();
    con.Close();
}