Julienn
Julienn

Reputation: 189

C# reading datagridview from one form to another form

I have two forms, one contains a datagridview control with a data source from MS Access. Data is properly displayed on the datagridview. First I select a cell in that data grid view, then I obtain the Row Index of the currently selected cell. I use that Row Index in an accessor function (code is in the main form):

public String Name
{ 
    get 
    { 
        return dataGridView1.Rows[selrow].Cells[1].Value.ToString(); 
    } 
}

selrow contains the row index of the currently selected cell. Next, I click a button "Edit record" and this it displays my 2nd form as a modal form. I want to display the value of the above accessor in a text box, so code goes like this (code is in the 2nd form):

private void EditRecord_Load(object sender, EventArgs e)
{
    CashLoan main = new CashLoan();
    txtEName.Text = main.name;
}

But when I try to run and debug, I get this "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" directed at my accessor function. I can't seem to find the source of the problem. Thank you in advance.

Upvotes: 0

Views: 1709

Answers (2)

Fabio
Fabio

Reputation: 32445

If I understand you want show value from main form in the textbox of Editrecord form. If so

In Load handler you create new instance of main form(CashLoan).
And trying read values from empty datagridview(I assume you not filling datagridview with data in the contructor) of main form.

Try pass your value to EditRecord form as parameter in contructor:
In EditRecord form:

private String _originalValue;
public EditRecord(String originalValue)
{
    _originalValue = originalValue;
}
//Then in Load handler
private void EditRecord_Load(object sender, EventArgs e)
{
    this.txtEName.Text = _originalValue;
}

//In main form
EditRecord frm = new EditRecord(this.name);
frm.ShowDialog();

Upvotes: 1

BudBrot
BudBrot

Reputation: 1411

Try

public String Name
{ 
    get 
    { 
        return dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString(); 
    } 
}

cause i guess you have a problem with the current selected row index. Also it would be possible that your row have only one cell. In that case replace the 1 with a 0 cause index starts at 0 (so 0 = 1, 1 = 2 etc...)

dataGridView1.Rows[selrow].Cells[0].Value.ToString(); 

Upvotes: 1

Related Questions