简体   繁体   中英

Return the value to a grid from a button click in c# windows application

In my C# windows application from a grid cell double click I am populating a Windows Form which is used to save the payment.So after payment the populated Form should pass the id to the grid and refresh the data in the grid. Nutshell:I need to implement this by using delegates and events as the grid values are populating from the db.Each time after payment the grid need to be refreshed.ie,Button in the second form should trigger the parent form to refresh datagrid based on the click returned value. Screenshot attached

Form1

private void dgvLoadBalance_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        long cellValue = long.Parse(dgvLoadBalance.Rows[e.RowIndex].Cells[2].Value.ToString());
        OPPaymentDatatable= commonDL.GetOpPaymentDetails(opRegId, cellValue);
        opDataTable = new DataTable();
        opDataTable.Columns.Add("PatientName", typeof(string));
        opDataTable.Columns.Add("DoctorName", typeof(string));
        opDataTable.Columns.Add("BillTypeName", typeof(string));
        opDataTable.Columns.Add("OPId", typeof(string));
        opDataTable.Columns.Add("OPNumber", typeof(string));
        opDataTable.Rows.Add(uctrlPatientSearch1.PatientName, uctrlPatientSearch1.DoctorName, uctrlPatientSearch1.BillTypeName, uctrlPatientSearch1.OPId,uctrlPatientSearch1.OPNumber);
        var settingsdt = commonBL.GetSettings();
        if (settingsdt.Rows.Count > 0 && settingsdt != null)
        {
            Address.Add(settingsdt.Rows[1][2]);
            Address.Add(settingsdt.Rows[2][2]);
            Address.Add(settingsdt.Rows[3][2]);
            Address.Add(settingsdt.Rows[4][2]);
            Address.Add(settingsdt.Rows[5][2]);
            Address.Add(settingsdt.Rows[6][2]);
            Address.Add(settingsdt.Rows[7][2]);
            Address.Add(settingsdt.Rows[8][2]);
        }
        frmPayOPBalance frmbalancepay = new frmPayOPBalance(OPPaymentDatatable, opDataTable, Address);
        frmbalancepay.ShowDialog();
    }

Form2

 private void btnPaynBill_Click(object sender, EventArgs e)
    {
        if (ValidateForm())
        {
            BindData();
            outVal = commonBL.InsertOpBalanceHistoryPayment(opPaymentModel);
            if (outVal > 0)
            {
                var dt = commonBL.GetOpBalanceBill(opPaymentModel);
                if (dt != null && dt.Rows.Count > 0)
                    opPaymentModel.BillNumber = long.Parse(dt.Rows[0]["BillId"].ToString());
                MessageBox.Show("Balance Payment made successfully", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                particularsDt = new DataTable();
                particularsDt.Columns.Add("Particulars", typeof(string));
                particularsDt.Columns.Add("Rate", typeof(string));
                particularsDt.Columns.Add("Amount", typeof(decimal));
                particularsDt.Rows.Add("OP Balance Payment for Reciept # " + opPaymentModel.OldBillId, string.Empty, opPaymentModel.BalAmount);
                BalancePaymentBillPrint objBalaPayPrint = new BalancePaymentBillPrint(opPaymentModel, Address, particularsDt);
                ClearBindings();
                this.Hide();
            }
            else
                MessageBox.Show("Error found in bill entry", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
        }
    }

A simple way is that you can use public properties and Application.OpenForms Property to achieve it.

Here is a demo. In this example, there is a DataGridView with two columns "ID" and "Number".

First, we need to define a property to access the DataGridView instance in Form1 .

public DataGridView DGV
{
    get { return dataGridView1; }
    set { dataGridView1 = value; }
}

Then define properties to get LabelID and TextBoxNumber in Form2 .

public Label LBID
{
    get { return labelID; }
    set { labelID = value; }
}

public TextBox TBNum
{
    get { return textBoxNumber; }
    set { textBoxNumber = value; }
}

Then pass values to Form2 via related properties.

// DataGridView in Form1
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    Form2 form2 = new Form2();
    form2.LBID.Text = dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString();
    form2.TBNum.Text = dataGridView1.Rows[e.RowIndex].Cells["Number"].Value.ToString();
    form2.Show();
}

Last, we can use Application.OpenForms Property in Form2 to get the Form1 instance to modify the DataGridview.

private void btnUpdate_Click(object sender, EventArgs e)
{
    Form1 form1 = (Form1)Application.OpenForms["Form1"];
    form1.DGV.Rows[Convert.ToInt32(labelID.Text) - 1].Cells["Number"].Value = textBoxNumber.Text;
    this.Close();
}

Test result:

在此处输入图像描述


Update: using delegate and event

Form1.cs

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //event handle method
    void frm_TransfEvent(int rowindex, string value)
    {
        // set Number column value
        dataGridView1.Rows[rowindex].Cells["Number"].Value = value;
    }

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        Form2 frm = new Form2();
        // pass rowindex to form2
        frm.ROWIndex = e.RowIndex;
        //subscribe to event
        frm.TransfEvent += frm_TransfEvent;
        frm.ShowDialog();
    }
}

Form2.cs

public delegate void TransfDelegate(int rowindex, string value);

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public event TransfDelegate TransfEvent;


    public int ROWIndex { get; set; }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        //trigger event
        TransfEvent(ROWIndex, textBox1.Text);
        this.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM