C# - 无法获取DataGridView中当前行的索引

时间:2016-01-22 14:45:34

标签: c# datagridview

如上所述,非常简单。使用以下代码,在修改单元格内容后,无论是否保留在当前行,都会出现以下错误。

注意:我只使用此方法调用进行故障排除。

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'
}

错误:

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

2 个答案:

答案 0 :(得分:1)

我正在使用asp:GridView我有一个带有编辑按钮的链接按钮我想获取我点击的项目的RowId所以我会在链接按钮点击事件上执行以下操作。

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

接下来,我将有一个事件并执行以下操作以确定在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;
}

答案 1 :(得分:0)

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