C# 获取 datagridview 最后一行索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17337331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:12:46  来源:igfitidea点击:

getting datagridview last row index

c#datagridviewtextbox

提问by user2491383

i'm trying to get the last row but the problem is....see my code

我正在尝试获取最后一行,但问题是......查看我的代码

Int32 index=dataGridveiw1.Rows.Count; // this is count start 1,2,3,4,5,6

sum3=txt_lotweight.Text-txt_balanceweight.Text;
sum4=datagridview1.Rows[index].Cells["rollweight"].Value-sum3;

how to minus gridview last row value to sum3 in this code error will come rows index not found because rows count start from 1 and when i subtract rows value to sum3 its start from 0

如何在此代码中将 gridview 最后一行值减去 sum3 错误将找不到行索引,因为行数从 1 开始,当我将行值减去 sum3 时,它从 0 开始

so how to get last row of gridview

那么如何获取gridview的最后一行

采纳答案by gzaxx

You are not getting last row index, but count that is higher by 1 than last index! That is because array indexing in C# starts from 0.

您没有获得最后一行索引,但计数比最后一个索引高 1!这是因为 C# 中的数组索引从 0 开始。

Int32 index = dataGridveiw1.Rows.Count - 1; // this is count start 1,2,3,4,5,6

this code will work. But I have doubts about your sum3- if your TextBoxcontains integers you should cast it to intbefore subtracting, and Valuein sum4 is object so casting is required as well.

这段代码会起作用。但是我对你的sum3- 如果你TextBox包含整数有疑问,你应该int在减去之前将它转换为,并且Valuesum4 是对象,所以也需要转换。

回答by vendettamit

Index are basically starts from 0 so if you are using the row count then you have to use it like this to get the last index.

索引基本上从 0 开始,所以如果您使用行数,那么您必须像这样使用它来获取最后一个索引。

Int32 index=dataGridveiw1.Rows.Count - 1 ;