当我从另一个表单打开它而不是datagrid的值时,组合框始终显示第一个值

时间:2018-04-16 19:42:49

标签: c#

我有一个包含两个组合框(cmbSection,cmbGrade)和两个文本框(txtName,txtSectionSize)的表单 我想从combobox和txtSectionSize获取文本并将其放在txtName中,这样我的代码就像这样锁定

 public partial class FRM_Item : Form
 {
    //public string State = "Add";
    BL.CLS_Item prd = new BL.CLS_Item();

    public FRM_Item()
    {
        InitializeComponent();

        cmbSection.DataSource = prd.Get_All_Items();
        cmbSection.DisplayMember = "Name_SectionType";
        cmbSection.ValueMember = "ID_SectionType";

        cmbGrade.DataSource = prd.Get_All_Grade();
        cmbGrade.DisplayMember = "Name_Grade";
        cmbGrade.ValueMember = "ID_Grade";
    }
private void cmbSection_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
    }

    private void cmbGrade_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;

    }

    private void txtSectionSize_TextChanged(object sender, EventArgs e)
    {
        this.txtName.Text = cmbSection.Text + txtSectionSize.Text + "-" + cmbGrade.Text;
    }

当我打开表单时,我在txtName中获取System.Data.DataRowView但是当我从combobox中获取任何文本时,我在文本框中获得正确的值 我通过将此代码移动到表单来解决此问题

        private void FRM_Item_Load(object sender, EventArgs e)
    {
        cmbSection.DataSource = prd.Get_All_Items();
        cmbSection.DisplayMember = "Name_SectionType";
        cmbSection.ValueMember = "ID_SectionType";

        cmbGrade.DataSource = prd.Get_All_Grade();
        cmbGrade.DisplayMember = "Name_Grade";
        cmbGrade.ValueMember = "ID_Grade";
    }

当我从另一种形式的按钮打开此表单时,我现在遇到的问题 组合框始终是第一个值,而不是来自datagrid的值

private void btnEdit_Click(object sender, EventArgs e)
    {
        FRM_Item frm = new FRM_Item();
        frm.txtName.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
        frm.cmbSection.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
        frm.txtSectionSize.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
        frm.cmbGrade.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();

        frm.ShowDialog();
    }

我如何解决这个问题

1 个答案:

答案 0 :(得分:0)

在分配组合框之前填​​充组合框。现在,它向后。

我建议将此代码移动到子窗体构造函数,或者在尝试在父窗体中分配属性之前调用可以调用的方法。

    cmbSection.DataSource = prd.Get_All_Items();
    cmbSection.DisplayMember = "Name_SectionType";
    cmbSection.ValueMember = "ID_SectionType";

    cmbGrade.DataSource = prd.Get_All_Grade();
    cmbGrade.DisplayMember = "Name_Grade";
    cmbGrade.ValueMember = "ID_Grade";

对于事件,如果你把代码放在构造函数中,你可以有一个boolean属性,如果你没有完成构造函数,或者没有在设计器中有事件,那么就不能运行事件代码在你填充组合框后的构造函数中。