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

问题描述 投票:0回答:1

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

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只是一种方法来做到这一点,但我需要两个表中的数据,但我这样做。

c# forms sqlite
1个回答
0
投票

我在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();
}

一切正常

© www.soinside.com 2019 - 2024. All rights reserved.