Lord Helmet
Lord Helmet

Reputation: 170

C# - Cannot get index of current row in DataGridView

Pretty simple, as mentioned. Using the following code, I get the following errors whether or not I stay in the current row after modifying cell contents.

NOTE: I am only using this method call for troubleshooting.

CODE:

private void handler_dataGridView1_CellValueChanged(object sender,DataGridViewCellEventArgs e){         
        try{Console.WriteLine(dataGridView1.CurrentCell.RowIndex);}catch{}      //'System.NullReferenceException'
        try{Console.WriteLine(dataGridView1.SelectedRows[0].Index);}catch{}     //'System.ArgumentOutOfRangeException'
        try{Console.WriteLine(dataGridView1.SelectedCells[0].RowIndex);}catch{} //'System.ArgumentOutOfRangeException'
        try{Console.WriteLine(dataGridView1.CurrentRow.Index);}catch{}          //'System.NullReferenceException'
}

ERRORS:

A first chance exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication4.exe
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
A first chance exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication4.exe

Upvotes: 0

Views: 1053

Answers (2)

MethodMan
MethodMan

Reputation: 18843

I am using asp:GridView and I have a Link Button that has Edit button I want to get the RowId of the item I clicked so I would do the following on the Link Buttons Click Event.

<asp:TemplateField HeaderText="Edit">
    <ItemTemplate>
        <asp:LinkButton ID="lnkEdit" Text="Edit" OnClick="lnkEdit_Click" runat="server" CausesValidation="false"></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

Next inside I will have an event and do the following to figure out what Row was clicked in the GridView

protected void lnkEdit_Click(object sender, EventArgs e)
{
    LinkButton lnk = sender as LinkButton;
    GridViewRow gr = (GridViewRow)lnk.NamingContainer;
    string tempID = gv.DataKeys[gr.RowIndex].Value.ToString();
    ViewState["KeyId"] = tempID;
}

Upvotes: 1

user5826941
user5826941

Reputation: 1

int SelectedRowIndex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[SelectedRowIndex];
string a = Convert.ToString(selectedRow.Cells["iDDataGridViewTextBoxColumn"].Value);

Upvotes: 0

Related Questions