使用C#表单中的相关字段与SQLite

时间:2017-12-10 10:22:51

标签: c# forms sqlite

我正在使用第二种形式编辑数据集中的记录,将BindingSource作为参数传递给第二种形式。我想使用一个引用的字段,即使用Employee表中的DEP编号来显示Department表中的部门名称

private void Form1_Load(object sender, EventArgs e)
{

    dbc.Open();

    departmentDataAdapter = new SQLiteDataAdapter("select * from DEPARTMENT", dbc);
    empDataAdapter = new SQLiteDataAdapter("select * from EMP", dbc);

    departmentDataAdapter.Fill(data, "DEPARTMENT");
    empDataAdapter.Fill(data, "EMP");

    relation = new DataRelation("EMPDPEP", data.Tables["DEPARTMENT"].Columns["DEPNO"], data.Tables["EMP"].Columns["DEPNO"]);
    data.Relations.Add(relation);

    masterBindingSource.DataSource = data;
    masterBindingSource.DataMember = "DEPARTMENT";
    detailsBindingSource.DataSource = masterBindingSource;
    detailsBindingSource.DataMember = "EMPDPEP";
}

private void EditButton2_Click(object sender, EventArgs e)
{
     Form2 detailsFrm = new Form2(detailsBindingSource); 
     detailsFrm.ShowDialog();
     if (detailsFrm.DialogResult == DialogResult.OK)
            {
                UpdateButton.BackColor = Color.Gold;
            }
            else
            {
                data.RejectChanges();
            }
}

public partial class Form2 : MetroFramework.Forms.MetroForm
{
    private BindingSource formDataSource;

    public Form2(BindingSource dataSource)
    {
        InitializeComponent();
        formDataSource = dataSource;


        TextBoxfName.DataBindings.Add("Text", formDataSource, "FNAME", true);
        // etc
    }
}   

该代码有效(我遗漏了很多东西以使其更清晰)但是dept名称不可用。我知道使用BindingSource只是一种方法来做到这一点,但我需要两个表中的数据但是我这样做。

1 个答案:

答案 0 :(得分:0)

I created a 'lookup table' for the combobox on Form2

public Form2(BindingSource dataSource)
{

SQLiteDataAdapter DEPDataAdapter = new SQLiteDataAdapter("select * from DEPARTMENT", dbc);
DataSet DEPdata = new DataSet();
DEPDataAdapter.Fill(DEPdata, "DEPARTMENT");

TextBoxEmpID.DataBindings.Add("Text", dataSource, "ID".ToString(), true);
TextBoxfName.DataBindings.Add("Text", dataSource, "FNAME", true);
TextBoxlName.DataBindings.Add("Text", dataSource, "LNAME", true);
TextBoxDEP.DataBindings.Add("Text", dataSource, "DEPNO".ToString(), true);
TextBoxComment.DataBindings.Add("Text", dataSource, "Comment", true);

ComboBoxDEP.DataSource = DEPdata.Tables["DEPARTMENT"];
ComboBoxDEP.DisplayMember = "DEPNAME";
ComboBoxDEP.ValueMember = "DEPNO";

ComboBoxDEP.SelectedValue = ((DataRowView)this.datasource.Current).Row["DEPNO"];

}

private void ComboBoxDEP_SelectionChangeCommitted(object sender, EventArgs e)
{
    TextBoxDEP.Text = ComboBoxDEP.SelectedValue.ToString();
}

That all works fine