简体   繁体   中英

How to update the column of datagridview from the text contents of textbox in c# Windows form

I have a datagridview with contents from a table. In that I have a column for Remarks which will be 1-2 lines. When I click on the remarks column, I want to open another form that contains the text box. I have linked the text box with the table using the table adapter. Now when I close the form with the text box, I want to show that in the datagridview column. Please help me

The way I've done this in the past is to pass a Action delegate to the second form that references a method from the first form.

The method you pass in contains the logic that updates your DataGridView.

Then in your second form closing event you call this delegate (after checking that it is not null) passing the value from your textbox.

Below is some quick prototype code to show how to do this. My method from Form1 just shows a message box, but you can easily change this to update your DataGridView datasource.

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form = new Form2();
        Action<string> showMessage = ShowMessage;
        form.ClosingMethod(showMessage);
        form.Show();
    }

    private void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
}

public partial class Form2 : Form
{
    private Action<string> _showMessage;

    public Form2()
    {
        InitializeComponent();
    }

    public void ClosingMethod(Action<string> showMessage)
    {
        _showMessage = showMessage;
    }

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_showMessage != null)
        {
            _showMessage("hippo");
        }
    }
}

Edit

Just occurred to me that the call to the delegate _showMessage("hippo"); is blocking.

Your form will not close until the delegate completes - potentially a long time. In my message box example, the form doesn't close until the OK button is clicked.

To get around this you can call your delegate asynchronously as shown below:

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    if (_showMessage != null)
    {
        _showMessage.BeginInvoke("hippo", null, null);
    }
}

如果您的DataGridView附加到具有TableAdapter的表,则以太必须自己更新单元,然后调用update将数据推回到表中,或者您可以从对话框更新表,然后刷新DataGridView。

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