sasib
sasib

Reputation: 1

getting datagridview row data to textboxes on another form

i have a datagridview that show my data in columns. what i'm trying to accomplish is that after choosing a row and pressing edit button a new form will open and split the row for the right text boxes to update the data.

the datagridview row shows different types of data: name,email,date,etc...

any idea? Thanks in advance!

Upvotes: 0

Views: 12884

Answers (2)

Daniel
Daniel

Reputation: 444

You can create a class, say MyDataCollection, with properties corresponding to your DataGridView columns. When you press the Edit button, create a new instance of this class, fill it with the necessary data and pass it as parameter to the EditForm's constructor.

public class MyDataCollection
{
    public string Name;
    public string Email;
    // -- 
}

In your main form:

void btnEdit_Click(object sender, EventArgs e)
{
    // Create the MyDataCollection instance and fill it with data from the DataGridView
    MyDataCollection myData = new MyDataCollection();
    myData.Name = myDataGridView.CurrentRow.Cells["Name"].Value.ToString();
    myData.Email = myDataGridView.CurrentRow.Cells["Email"].Value.ToString();
    // --

    // Send the MyDataCollection instance to the EditForm
    formEdit = new formEdit(myData);
    formEdit.ShowDialog(this);
}

And the edit form should look like this:

public partial class formEdit : Form
{
    // Define a MyDataCollection object to work with in **this** form
    MyDataCollection myData;

    public formEdit(MyDataCollection mdc)
    {
        InitializeComponent();

        // Get the MyDataCollection instance sent as parameter
        myData = mdc;
    }

    private void formEdit_Load(object sender, EventArgs e)
    {
        // and use it to show the data
        textbox1.Text = myData.Name;
        textbox2.Text = myData.Email;
        // --
    }
}

You can also forget about the MyDataCollection class and pass the entire DataGridViewRow to the formEdit's constructor.

Upvotes: 2

RhysW
RhysW

Reputation: 453

This site explains how to send data between forms, it would be as simple as selecting the right cell in the datagrid, sending that info off to the right textbox, for all of them. then sending them back. Data between forms

The basics are to create a method that can be use to get the value,

    public string getTextBoxValue()
{
    return TextBox.Text;
}

then you can just call the method to pass the data between the forms,

this.Text = myForm2.getTextBoxValue();

however you will be sending the values of the cells, and will be making a textbox.text equal to the return of the method this is a basic example of the theory, giev it a try yourself to make it work for what you want it to do, if you just cant do it come back and ask for help and ill edit with the code, but only after youve tried yourself first

Upvotes: 2

Related Questions